Secure Multi-Tenant Pipeline for Big Ledger File Processing
System DesignModel answerLast updated
Design a service where enterprise tenants upload files up to 5 GB, which are processed asynchronously into versioned reconciliation reports, with resumable uploads, idempotent jobs, and strict isolation.
Problem
A payments platform lets enterprise customers submit very large batch files (transaction ledgers, bank statements, payment batches) in CSV, XML, or JSON, up to 5 GB each. After submission, the platform must validate and parse the records and produce reconciliation and compliance reports.
Design an authenticated service that accepts these uploads, analyzes them asynchronously, and publishes versioned reports, while keeping each tenant's data strictly separate.
Functional requirements
- Resumable uploads: files up to 5 GB must survive flaky connections, using chunked or multipart transfer.
- Asynchronous analysis: once an upload is assembled and verified, start a background validation and processing pipeline.
- Idempotency and dedup: the same file, or a repeated trigger or webhook, must not be processed twice.
- Versioned reports: produce reports (JSON and/or PDF summaries of anomalies and reconciled balances) that authorized users of the tenant can fetch, with each new run creating a new version.
- Tenant isolation: no cross-tenant access in storage, in transit, or in compute.
Non-functional requirements
- Reliability: an interrupted upload resumes without restarting from byte 0. A crashed worker never leaves a job stuck.
- Scale: 10,000 uploads per day, with bursts of 50 concurrent large-file jobs.
- Security: short-lived presigned access, encryption at rest and in transit, strict RBAC.
- Latency: upload-init and upload-complete API calls respond within 200 ms. A 5 GB file is analyzed within 10 minutes.
What your answer should cover
- API design: endpoints to start an upload, track or register parts, finish the upload, and query job and report status.
- Storage: object layout, how parts are assembled, lifecycle rules.
- Processing pipeline: queues, worker pools, streaming and parallel parsing, job state management.
- Idempotency and recovery: network drops, duplicate requests, workers dying mid-task, and poisoned (malformed) records.
- Multi-tenancy: isolation in the data tier and fair sharing in the compute tier (rate limits, quotas).
Hints
Hint 1
Do the back-of-envelope math first: 10,000 uploads/day is a tiny request rate, so the real constraints are the 10-minute SLA for 5 GB (about 8.5 MB/s sustained) and fairness during bursts. That suggests splitting each file into shards.
Hint 2
Keep file bytes off your API servers: clients upload parts directly to object storage through presigned URLs, and the 'complete' call should only record intent and return quickly, with a background worker doing the actual assembly.
Hint 3
Make every stage safe to retry: use a unique dedupe key on jobs, deterministic output paths per shard, leases with heartbeats for workers, and a retry limit that diverts bad records or shards to a dead-letter/quarantine path.
Hint 4
For tenant isolation, think in layers: tenant ID taken from the auth token (never the body), per-tenant prefixes and encryption keys, row-level security in the database, and per-tenant concurrency quotas in the scheduler.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The core ideas: keep large bytes off the control plane, make every pipeline stage retry-safe, and prevent one tenant from affecting another. I would state these up front and then back them with numbers and a clear state machine.
1. Scale and assumptions
- 10,000 uploads/day is roughly 0.12/s on average, so request throughput is trivial. The hard parts are per-job latency and fairness during bursts.
- With an assumed 300 MB average file, that is about 3 TB/day of raw data (about 1 PB/year before tiering). Worst case, all files at 5 GB, is about 50 TB/day.
- Finishing 5 GB in 10 minutes needs about 8.5 MB/s end to end. A single streaming parser with validation does maybe 30-80 MB/s, so one worker could technically make it but with no margin. Shard the work (about 256 MB each, around 20 shards per big file) so slow nodes and retries do not blow the deadline.
- 50 concurrent big jobs x about 20 shards is around 1,000 shard tasks at peak. Plan for roughly 200-300 parallel workers with autoscaling.
- Recommend NDJSON over a single JSON array so files can be split on newlines.
2. API design
All calls require a JWT, and tenant_id is derived from the token, never the body.
POST /v1/uploads (Idempotency-Key header)
{filename, size_bytes, format, schema_version, sha256?}
-> 201 {upload_id, part_size, part_count, part_urls[], expires_at}
GET /v1/uploads/{id} -> {state, parts_received:[{n, etag}]}
POST /v1/uploads/{id}/part-urls {part_numbers[]} -> fresh presigned URLs
POST /v1/uploads/{id}/complete {parts:[{n, etag, crc32c}]} -> 202 {job_id}
GET /v1/jobs/{job_id} -> {state, progress, error_summary}
GET /v1/reports/{id}/versions -> list of versions
GET /v1/reports/{id}/versions/{v} -> 302 to short-lived presigned download
POST /v1/webhooks register endpoint + signing secret
Meeting 200 ms:
- Init writes one DB row, calls
CreateMultipartUpload, and signs URLs locally (CPU only, no network). - Complete validates the part list, sets state
COMPLETING, writes an outbox event, and returns202. An assembler worker callsCompleteMultipartUpload, which can take seconds.
Resumability: 64 MB parts give about 80 parts for 5 GB, far below the 10,000-part limit. The client uploads 3-6 parts in parallel straight to object storage. After a drop it calls GET /uploads/{id} (backed by ListParts) and sends only missing parts. Per-part CRC32C catches corruption.
3. Data model
uploads(upload_id, tenant_id, key, mp_upload_id, size, declared_sha256, state)jobs(job_id, tenant_id, upload_id, dedupe_key UNIQUE, state, attempt, lease_owner, lease_expires_at, shards_total, shards_done)shards(job_id, shard_no, byte_start, byte_end, state, attempts, output_key)reportsand immutablereport_versions(version, rules_version, parser_version, job_id, object_key)idempotency_keys(tenant_id, key, request_hash, response)with a 24 h TTLoutbox(event_id, payload, published_at)
Postgres row-level security enforces tenant_id = current_setting('app.tenant') on every query.
4. Storage
raw-ingest/{tenant}/{date}/{upload_id}/source
work/{tenant}/{job}/shard-{n}.parquet, errors-{n}.ndjson
reports/{tenant}/{report}/v{n}/report.{json,pdf}
- SSE-KMS with a per-tenant key, enabling independent revocation or crypto-shredding.
- TLS everywhere. Presigned URLs are bound to one key and part number, last about 15 minutes, and fix content length.
- Lifecycle: abort incomplete multipart uploads after 3 days (a classic silent cost), delete
work/after 7 days, tier raw data to infrequent access at 30 days and then archive, and keep reports and raw files for the compliance period (for example 7 years) with object lock. - Quarantine: a file is invisible to parsers until malware scanning and a format check pass.
5. Processing pipeline
State machine: UPLOADING -> COMPLETING -> UPLOADED -> QUEUED -> VERIFYING -> SPLITTING -> PROCESSING -> AGGREGATING -> RENDERING -> SUCCEEDED | PARTIAL | FAILED.
- The outbox relay publishes
upload.completed; the job creator inserts a job row. - Verify: stream the object once, compute the server-side SHA-256 (the client hash is only a hint), and sniff the format.
- Split: CSV into byte-range shards, advancing each boundary to a record start. Quoted newlines make this ambiguous, so either pre-scan quote-aware or require RFC 4180 and check joins. NDJSON splits at newlines. XML is handled with one SAX pass or split on a repeating element.
- Process: each shard task does a Range GET, validates and normalizes rows, and writes deterministic outputs (a partial aggregate in Parquet, plus an error file). Memory stays constant.
- Aggregate: when an atomic counter shows
shards_done == shards_total, merge partials into balances, anomalies, and duplicate-transaction checks. - Render: write JSON/PDF, insert a new
report_versionsrow, emitreport.ready.
Use separate queues per stage (SQS or Kafka) and autoscale workers on queue depth and oldest-message age.
6. Idempotency and failure recovery
- API replays: the
Idempotency-Keyreturns the stored response. The same key with a different body returns409. - Duplicate files or triggers:
dedupe_key = sha256(tenant | file_sha256 | schema_version | rules_version)withINSERT ... ON CONFLICT DO NOTHING. If it exists, return the existing job or report. Changing rules or schema version intentionally yields a new report version. - Worker crashes: tasks hold a lease with heartbeats. If the lease expires, the task is requeued. Because outputs are written to deterministic keys and then committed atomically (write temp, rename or conditional state update), re-execution is harmless. At-least-once delivery plus idempotent tasks gives effectively-once results.
- Network drops: covered by resumable parts. Webhook delivery is retried with exponential backoff and a signed event ID so receivers can dedupe.
- Poisoned records: bad rows go to the error file with line number and reason, not failing the job. If the error rate exceeds a threshold (say 5%), fail the job fast. A shard that crashes the worker repeatedly (3 attempts) goes to a dead-letter queue and the job ends as
PARTIALorFAILEDwith a clear report.
7. Multi-tenancy and fairness
- Data tier: per-tenant prefixes, KMS keys, IAM policies conditioned on tenant, and RLS in the database. Presigned URLs are minted only after the token's tenant is checked.
- Compute tier: per-tenant concurrency caps and API rate limits. The scheduler uses weighted fair queuing so a tenant submitting 500 files cannot starve others, with an optional reserved capacity tier for large customers. Resource limits (CPU, memory, ephemeral disk) are set on every worker. Parsing runs in sandboxed containers because the input is untrusted.
- RBAC: roles such as uploader, viewer, and admin, plus audit logs for every download.
Trade-offs and common mistakes
- Proxying file bytes through API servers kills scalability. Use direct-to-storage uploads.
- Doing assembly inside the complete call breaks the 200 ms budget.
- Trusting the client hash or tenant ID in the body is a security hole.
- Forgetting to abort stale multipart uploads leaks storage cost.
- Naively splitting CSVs on newline corrupts records with quoted line breaks.
- Non-deterministic outputs make retries produce duplicates. Prefer deterministic keys and atomic commits.
- Single-queue FIFO with no per-tenant limits causes noisy-neighbor problems.