Course contentsShow
← System Design
Lesson 1904 of 1,91945. API Design and VersioningFree lesson

Maintaining Multiple API Versions

Code organization strategies for supporting concurrent versions without duplicating logic.

Maintaining Multiple API Versions

What you'll learn: How to organize your codebase to support multiple concurrent API versions without duplicating business logic everywhere.

The Challenge

After introducing versioning strategies (URI, header, or query-based), you face a practical problem: how do you actually maintain v1, v2, and v3 in the same codebase without copy-pasting everything? Naively duplicating controllers, services, and models for each version creates a maintenance nightmare.

Code Organization Strategies

1. Shared Core with Version-Specific Adapters

Keep your business logic in a single, version-agnostic core layer. Each API version has a thin adapter (controller/serializer) that translates requests/responses to the format that version expects. Think of it like electrical plug adapters—same power source, different shapes.

2. Feature Flags and Conditional Logic

For minor differences, use runtime checks: if (version >= 2) { includeNewField(); }. Works well for additive changes but gets messy with breaking changes.

3. Separate Routers, Shared Services

Route /v1/users and /v2/users to different controllers, but both call the same UserService. Controllers handle serialization differences; services handle business rules.

4. Version-Specific DTOs (Data Transfer Objects)

Use distinct request/response models per version (UserV1Response, UserV2Response) while keeping domain models unchanged. Mapping layers convert between versions and core entities.

5. Deprecation with Forwarding

Old versions can forward to new versions with compatibility shims—v1 calls v2 internally with default values for new required fields.

Key Takeaway:
Isolate version differences at API boundaries (controllers, serializers) while keeping business logic and data models version-agnostic; use adapters and mapping layers to translate between external contracts and internal representations.