Client for migrating records between REST APIs with OAuth
System DesignModel answerLast updated
Write a CLI tool that authenticates via OAuth 2.0, fetches paginated data from one API, transforms it, and posts it to another with checksums and idempotency.
You need to design and implement a command-line tool that migrates user records from an old REST API to a new one. The tool must authenticate using OAuth 2.0, handle pagination, transform data formats, ensure data integrity with checksums, and be resilient to failures.
Requirements
Your tool should:
- Authenticate using OAuth 2.0 Client Credentials flow
- Fetch records from the source API (supports pagination)
- Transform each record according to specified mapping rules
- Upload transformed records to the destination API
- Compute integrity checksums for each upload
- Handle failures gracefully with retries and resumability
API Specifications
Authentication Endpoint
POST https://auth.service.io/token
Content-Type: application/json
Request body:
{
"client_id": "your_client_id",
"client_secret": "your_secret",
"grant_type": "client_credentials"
}
Response:
{
"access_token": "eyJhbG...",
"expires_in": 3600
}
Source API (Legacy System)
GET https://old-api.service.io/users?page=<n>&limit=<k>
Authorization: Bearer <token>
Response:
{
"users": [
{
"user_id": 42,
"given_name": "Grace",
"family_name": "Hopper",
"contact_email": "[email protected]",
"registered_ts": 1609459200,
"account_status": "ACTIVE"
}
],
"next_page": 2
}
When next_page is null, you've reached the end.
Destination API (New System)
POST https://new-api.service.io/users
Authorization: Bearer <token>
Content-Type: application/json
X-Integrity-Hash: <sha256_hex>
Idempotency-Key: <unique_stable_id>
Request body (one record):
{
"source_id": 42,
"name": "Grace Hopper",
"email": "[email protected]",
"registered_at": "2021-01-01T00:00:00Z",
"active": true
}
Data Transformation Rules
Map each source record to the destination format:
source_id←user_idname←given_name + " " + family_name(normalize whitespace)email← lowercase(contact_email)registered_at← convertregistered_ts(Unix epoch) to ISO 8601 UTC stringactive←trueifaccount_status == "ACTIVE", otherwisefalse
Checksum Calculation
The X-Integrity-Hash header must contain the SHA-256 hash of the exact JSON bytes you send. Use a canonical JSON representation (sorted keys, no extra whitespace) to ensure consistency across retries.
Operational Requirements
- Token management: Refresh tokens before they expire; handle 401 responses by re-authenticating
- Retry logic: Retry transient failures (network errors, 429, 5xx) with exponential backoff
- Idempotency: Use stable idempotency keys (derived from
user_id) so rerunning the tool doesn't create duplicates - Resumability: Track progress so the tool can resume after crashes without reprocessing everything
- Logging: Report progress, errors, and any records that fail validation
Deliverables
Provide:
- Design document (1-2 pages) explaining your architecture, data flow, error handling strategy, and how you ensure idempotency
- Implementation in your preferred language
- Test strategy covering transformation logic, checksum generation, and how you would mock the APIs
Discuss trade-offs in your design choices (e.g., sequential vs. parallel uploads, memory usage, fault tolerance).
Hints
Hint 1
Separate pure transformation functions from I/O so they can be unit tested independently
Hint 2
Manage token lifecycle proactively—refresh before expiration rather than waiting for 401s
Hint 3
Use the source record ID to generate stable idempotency keys that remain the same across retries and restarts
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Design Overview
The solution follows a pipeline architecture: authenticate → paginate → transform → verify → upload → checkpoint. Separating concerns makes each stage independently testable and allows the system to recover from failures at any point.
Core Components
1. Token Manager
Maintains the OAuth access token with proactive refresh. It fetches a new token when:
- No token exists yet
- Current time exceeds
expires_in - safety_margin(e.g., 60 seconds before expiration) - The API returns 401 Unauthorized (indicates premature revocation)
This avoids most authentication failures and handles clock skew gracefully. The manager should only retry authentication once per request to prevent infinite loops when credentials are truly invalid.
2. Transformation Layer
Pure functions that map source schema to destination schema:
def transform_record(source):
given = source.get("given_name", "").strip()
family = source.get("family_name", "").strip()
full_name = " ".join([given, family]).strip()
epoch = source["registered_ts"]
registered = datetime.utcfromtimestamp(epoch).strftime("%Y-%m-%dT%H:%M:%SZ")
return {
"source_id": source["user_id"],
"name": full_name,
"email": source["contact_email"].lower().strip(),
"registered_at": registered,
"active": source.get("account_status") == "ACTIVE"
}
Edge cases:
- Missing or null name fields → empty string handling prevents crashes
- Extra whitespace in names →
strip()andsplit()/join()normalize - Non-ASCII characters → preserve UTF-8 encoding throughout
- Case-insensitive email normalization → always lowercase
- Status values → only exact match "ACTIVE" returns true
3. Checksum Generation
To ensure integrity, compute SHA-256 over the exact bytes sent:
def compute_checksum(record):
# Canonical JSON: sorted keys, compact format, UTF-8
json_bytes = json.dumps(
record,
sort_keys=True,
separators=(',', ':'),
ensure_ascii=False
).encode('utf-8')
return hashlib.sha256(json_bytes).hexdigest()
Critical: serialize once and send those exact bytes. If you pass a dict to the HTTP library's json parameter, it may serialize differently (different key order, spacing), producing a different checksum than you computed.
4. Retry Logic
Implement exponential backoff with full jitter for transient failures:
def fetch_with_retry(request_fn, max_attempts=5):
for attempt in range(max_attempts):
try:
response = request_fn()
if response.status_code < 500 and response.status_code != 429:
return response
except (Timeout, ConnectionError):
pass
if attempt < max_attempts - 1:
base_delay = 0.5 * (2 ** attempt)
jitter = random.uniform(0, base_delay)
time.sleep(min(jitter, 30))
raise RetryExhausted()
Retry on:
- Network errors (timeout, connection refused)
- 429 Too Many Requests (respect
Retry-Afterheader if present) - 5xx server errors
Don't retry:
- 4xx client errors (except 429) → these are permanent, log and skip
- Successful responses (2xx, 3xx)
5. Idempotency Strategy
Two layers ensure exactly-once semantics:
Layer 1 - Stable keys: Generate idempotency keys from source IDs:
Idempotency-Key: migration-user-42
The destination API deduplicates requests with the same key. Treat 409 Conflict as success.
Layer 2 - Checkpoint file: Track the last fully processed page:
{"last_completed_page": 5}
Write this file only after successfully uploading all records from a page. On restart, resume from last_completed_page + 1. This provides at-least-once delivery at the page level, with idempotency keys ensuring no duplicates.
6. Pagination Loop
page = load_checkpoint() + 1
while True:
response = fetch_page(page)
records = response["users"]
for record in records:
transformed = transform_record(record)
upload_record(transformed)
if response["next_page"] is None:
break
save_checkpoint(page)
page = response["next_page"]
Error Handling
Permanent failures: Invalid data, 400/422 responses → log to dead-letter file with reason, continue processing other records
Transient failures: After exhausting retries on a GET, abort and let checkpoint enable clean restart. On POST failures, the idempotency key makes retry safe.
Token expiry: 401 response triggers immediate token refresh and single retry. Prevents cascading failures.
Performance Considerations
Sequential vs. Parallel:
- Sequential uploads are simpler and sufficient for moderate datasets
- For large migrations, use a thread pool (e.g., 10 workers) to process pages in parallel
- Each page needs its own checkpoint to track progress safely
Memory usage: O(page_size) by processing one page at a time. For very large pages, consider streaming or sub-paging.
Network efficiency: Could batch multiple records per POST if the destination API supports it. This reduces round trips but complicates idempotency (need batch-level keys).
Testing Strategy
Unit tests:
- Transformation logic with various edge cases (missing fields, whitespace, UTF-8)
- Checksum generation with known inputs
- Retry backoff calculation
Integration tests with mocked APIs:
- Use
responseslibrary (Python) or equivalent to mock HTTP endpoints - Test pagination until
next_pageis null - Simulate token expiry mid-migration
- Inject 429/503 errors to verify retry behavior
- Verify idempotency keys are stable across runs
Contract tests:
- Validate actual API responses match documented schemas
- Useful when migrating against real staging environments
Complexity Analysis
- Time: O(N) where N is total records. Each record is fetched once, transformed once, uploaded once. Wall-clock time dominated by network latency.
- Space: O(P) where P is page size. Only one page held in memory at a time.
Production Readiness
For a real migration:
- Add metrics (records/sec, error rates) and alerting
- Support dry-run mode to validate transformations without uploading
- Implement checksum verification on destination API reads
- Add data validation layer before upload (email format, required fields)
- Consider rate limiting to avoid overwhelming destination API
- Store detailed audit log for compliance/debugging
This design balances simplicity with robustness, ensuring the migration can complete even with intermittent failures while preventing data loss or duplication.