Background Job API for Hierarchical Data Replication
System DesignModel answerLast updated
Design an endpoint that replicates a multi-level data hierarchy with automatic identifier reassignment, progress tracking, and fault tolerance.
You're building a service that manages collections of evaluation data. The storage hierarchy has four levels: a collection holds items, each item has submissions, and each submission has assessments. All relationships use foreign keys in a relational database.
Design an API endpoint that replicates an entire collection along with all nested items, submissions, and assessments. The replica must be fully independent—modifications to either the original or the replica should never affect the other.
Requirements
Your design should address:
-
Small collections: For collections that finish quickly, define the endpoint contract and explain how foreign key references are updated to point to newly created rows rather than the originals.
-
Large collections: When replication takes too long for a single HTTP request, restructure the operation to run asynchronously with progress visibility and the ability to recover from interruptions without losing completed work.
-
Reliability: Handle duplicate requests from clients and prevent multiple worker processes from executing the same replication simultaneously.
-
Concurrent modifications: Decide what happens when the source collection is modified during replication, and define cleanup behavior when replication fails partway through.
Areas to Consider
- How do you maintain referential integrity when every row receives a new primary key?
- What data structures support resumable progress after a crash?
- How do clients distinguish between a new replication request and a retry of an existing one?
- What mechanisms prevent two workers from processing the same job?
- Should the replica reflect the source at job start time, or can it include changes made during replication?
- When should partial replicas be visible to users, and when should they be removed?
Hints
Hint 1
Consider how a mapping table from old IDs to new IDs can be persisted and used across restarts
Hint 2
Think about what database constraints or application-level checks can ensure a request creates only one job even if submitted multiple times
Hint 3
For worker coordination, explore how a timestamp field or version counter on the job record can serve as a lease mechanism
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Synchronous Replication for Small Collections
API Contract
POST /api/collections/{id}/replicate
Response: 201 Created
{
"collection_id": "new-uuid",
"created_at": "2025-01-15T10:30:00Z"
}
The endpoint returns the identifier of the newly created collection immediately upon completion.
Replication Process
Copy rows in dependency order: collection first, then items referencing that collection, then submissions referencing those items, finally assessments referencing those submissions. As each row is copied, store the mapping from its original ID to its newly assigned ID.
For example, if the original collection has id=100 and items [200, 201], the replication might produce collection_id=500 and item_ids=[600, 601]. When copying submissions that reference item_id=200, rewrite that reference to item_id=600 using the mapping.
Atomicity: Wrap the entire replication in a database transaction. Either all rows commit together or none do, preventing partial replicas from becoming visible.
Complexity: For N total rows and average depth D, the approach runs in O(N) time and O(N) space for the ID mapping.
Part 2: Asynchronous Replication with Resumability
Job Lifecycle API
POST /api/collections/{id}/replicate
Response: 202 Accepted
{
"job_id": "job-uuid",
"status": "pending"
}
GET /api/replication-jobs/{job_id}
Response: 200 OK
{
"job_id": "job-uuid",
"status": "running",
"progress": {
"items_copied": 450,
"items_total": 1000,
"percent": 45
},
"result": null
}
When complete, the status becomes "completed" and result contains the new collection ID.
Persistent State Schema
CREATE TABLE replication_jobs (
id UUID PRIMARY KEY,
source_collection_id UUID NOT NULL,
target_collection_id UUID,
status VARCHAR(20), -- pending, running, completed, failed
last_checkpoint TEXT, -- JSON: {"level": "items", "last_id": 300}
created_at TIMESTAMP,
updated_at TIMESTAMP
);
CREATE TABLE id_mappings (
job_id UUID NOT NULL,
entity_type VARCHAR(20), -- collection, item, submission, assessment
source_id UUID NOT NULL,
target_id UUID NOT NULL,
PRIMARY KEY (job_id, entity_type, source_id)
);
Batching and Checkpointing
Process each level in batches of, say, 100 rows. After copying a batch and writing the ID mappings, commit the transaction and update last_checkpoint with the highest source ID processed at that level.
On restart, read the checkpoint to determine which level was in progress and the last ID completed. Resume from the next ID in sequence. The ID mappings table is already populated for completed rows, so foreign keys are rewritten correctly for subsequent levels.
This approach ensures that if a worker crashes after copying items 1–300, a new worker resumes at item 301 without reprocessing the first batch.
Part 3: Request Deduplication and Worker Coordination
Idempotency
Use a unique request identifier provided by the client or derived from the source collection ID and a client-generated nonce:
POST /api/collections/{id}/replicate
Headers:
Idempotency-Key: client-generated-uuid
When the request arrives, atomically insert a job record with the idempotency key. If a row with that key already exists (unique constraint violation), return the existing job ID instead of creating a new one. The second request receives the same job ID and can poll for its status.
Worker Leasing
Add lease fields to the job table:
ALTER TABLE replication_jobs ADD COLUMN worker_id VARCHAR(50);
ALTER TABLE replication_jobs ADD COLUMN lease_expires_at TIMESTAMP;
A worker claims a job with an atomic compare-and-swap:
UPDATE replication_jobs
SET status = 'running',
worker_id = 'worker-7',
lease_expires_at = NOW() + INTERVAL '5 minutes'
WHERE id = ? AND (status = 'pending' OR lease_expires_at < NOW());
If the update affects zero rows, another worker already holds the lease. Otherwise, this worker proceeds.
Heartbeat: Every 60 seconds, the worker extends lease_expires_at. If the worker crashes, the lease expires and another worker can claim the job.
Stale Worker Protection: Before writing each batch, verify that (worker_id, lease_expires_at) still match the worker's expected values. If they don't, abort immediately—another worker has taken over.
Part 4: Consistency and Failure Handling
Handling Concurrent Edits to the Source
Option A: Snapshot Isolation
Start a long-running read-only transaction with REPEATABLE READ or SERIALIZABLE isolation before beginning the copy. All reads see the source collection as it existed at transaction start.
Trade-off: Holding a transaction open for minutes consumes database resources and may block vacuuming or schema changes. For very long jobs, this is impractical.
Option B: Best-Effort Consistency
Copy rows using independent queries per batch. If the source is edited during the copy, the replica may contain a mix of old and new states—internally inconsistent.
Mitigation: Add a snapshot_timestamp field to the job, record it at job start, and include a WHERE updated_at <= snapshot_timestamp filter in all copy queries. This requires the source tables to track updated_at, and it excludes rows modified after the job began, but rows created mid-job with an old timestamp could still slip in.
Recommendation: For most use cases, Option B with timestamp filtering provides acceptable consistency without locking the source.
Visibility of In-Progress and Failed Replicas
In-progress: The target collection exists but is marked draft=true or status='replicating'. Queries that list collections exclude drafts by default, hiding incomplete replicas from users.
Failed: When a job fails after exhausting retries, leave the partial replica in place but mark it status='failed'. Provide a cleanup endpoint:
DELETE /api/replication-jobs/{job_id}
This endpoint deletes the target collection and all copied children in a cascading transaction, then marks the job status='deleted'.
Auto-cleanup: A scheduled task can delete failed jobs older than 7 days.
Resumption vs. Full Cleanup
Resume when the failure is transient (network timeout, temporary database overload). The checkpoint mechanism allows continuing from the last committed batch.
Clean up and restart when the failure is structural (schema change, source collection deleted, foreign key violation). Detect these by checking the error type in the worker's exception handler.
Summary
A strong design clearly separates concerns: synchronous replication for small jobs with transactional atomicity; asynchronous execution with durable checkpoints and ID mapping tables for large jobs; idempotency keys and worker leasing for reliability; and timestamp-based filtering with explicit draft/failed states for consistency and failure handling. Operational metrics like jobs completed per hour, average replication time, and failure rate by error type provide visibility into system health.