Build a Scheduler and Runner Platform for Automated Test Suites
System DesignModel answerLast updated
Design a platform where teams declare automated tests, trigger or schedule them, run them on shared compute, and query status, logs, artifacts and history reliably at scale.
Problem
Your engineering organization wants a single internal platform that runs automated tests on demand and on a timetable. Design it.
The brief is deliberately loose. Start by asking clarifying questions, write down the assumptions you make (team count, run volume, kinds of compute), and then propose an architecture you can defend.
What your design should cover
- Test definitions. How a test is described, versioned and configured (image, command, resources, timeout, retry policy, parallelism, required hardware or labels).
- Triggering. How users start a run by hand, from a code-change event, or through a recurring schedule.
- Dispatch. How units of work reach executors, including heterogeneous ones (plain containers, GPU hosts, physical devices).
- Observability and storage. How status, live logs, artifacts and per-test results are stored and queried, including historical questions such as "is this test flaky?".
- Robustness. How you deal with crashed workers, retries, timeouts, cancellation, concurrency caps, fairness between teams, and growth in load.
- Interfaces. The public API, the worker-facing protocol and the core data model.
Expectations
- Give rough capacity numbers and justify your storage choices with them.
- Explain the state machine for a unit of work and what guarantees you offer (for example at-least-once execution).
- Call out trade-offs and what you would change at 10x scale.
Hints
Hint 1
Separate the 'what to run' (an immutable, versioned definition) from 'one execution of it' (a run split into tasks). Every run should record the exact definition version it used.
Hint 2
Consider a pull model where workers lease tasks with an expiry and a fencing token, heartbeat while working, and have a reaper requeue expired leases. Ask what happens if a stale worker reports late.
Hint 3
Treat infrastructure failures and genuine test failures differently for retries, and decide where concurrency and fairness limits are enforced (hint: at lease time, per pool, team and definition). Use different stores for transactional metadata, blobs, and high-volume analytical results.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
Functional scope
- Several test kinds: unit and integration suites, end-to-end, load tests, and possibly hardware-in-the-loop.
- Triggers: manual (UI, CLI, API), CI events (pull request, merge) and cron schedules.
- Execution on mixed compute: containers, GPU machines, physical devices.
- Real-time status, streamed logs, artifacts, searchable history, retries, timeouts, cancellation, concurrency limits.
Assumed scale (state these aloud)
- About 2,000 engineers, 50k runs/day, roughly 10 shards per run, so about 500k tasks/day. That is about 6 tasks/s on average and perhaps 50/s at peak.
- Logs near 1 MB per task gives about 500 GB/day. Artifacts such as videos and core dumps add maybe 2 TB/day, kept 30 to 90 days.
- Guarantees: no lost runs, at-least-once task execution with idempotent handling of duplicates, status visible within about 2 s, control plane at 99.9%. Workers are allowed to disappear at any time.
Out of scope: the CI system itself and test authoring tools.
2. Data model
Keep the definition separate from its executions.
| Entity | Key fields |
|---|---|
| TestDefinition | id, name, owner team, type, immutable version (content hash), spec (image, command, env, resources, timeout, retry policy, shard count, pool/labels), source git sha |
| Schedule | id, definition id, version selector (pinned or latest), cron, timezone, params, enabled, next_fire_at |
| Run | id, definition id, version, trigger, params, status, requester, created_at, idempotency_key |
| Task | id, run id, shard index, attempt, status, worker id, lease_expires_at, lease_token, started/finished, exit code |
| TestResult | task id, case name, status, duration, failure message |
| Artifact | task id, name, blob URI, size, content type |
| Pool / Quota | pool labels and capacity; caps per team, definition and named resource |
Versioning: keep definitions as YAML in the repository so review, diff and rollback come free. On merge, sync them into a registry, creating a new immutable version per change. A run stores the version it executed, so any historical result can be reproduced.
Storage choices
- Postgres for definitions, schedules, runs and tasks: small volume, needs transactions.
- Object storage for logs and artifacts, with lifecycle rules for retention.
- Columnar store (ClickHouse or BigQuery) for per-case results: millions of rows/day, queried for trends and flakiness.
3. APIs
POST /definitions (or git sync)
POST /runs {definition_id, version?, params, idempotency_key}
POST /runs/{id}/cancel
POST /runs/{id}/rerun {only_failed}
GET /runs?definition=&status=&since=
GET /runs/{id}
GET /tasks/{id}/logs?follow=true (SSE or WebSocket)
POST /schedules {definition_id, cron, tz, version_selector, params}
GET /tests/{case}/history (pass rate, flakiness, p50/p95)
Worker gRPC:
LeaseTask(pool, labels), Heartbeat(task_id, token),
ReportResult(task_id, token, status, results, artifact_uris)
4. Architecture
Clients and CI call an API gateway, which fronts a Run Service. The Run Service validates input, resolves the definition version, and in one transaction inserts a Run plus N Task rows, deduplicating on the idempotency key. A Scheduler service scans next_fire_at and creates runs through the same path. A Dispatcher exposes per-pool queues of ready tasks and enforces quotas. Workers (Kubernetes pods, device hosts) lease tasks, run them in isolation, stream logs, upload artifacts and report results. A Reaper handles expired leases. A Result Ingest service parses JUnit-style output into the columnar store and emits events for chat notifications and pull-request status.
5. Deep dives
Dispatch (pull with leases). Workers know their own capacity and labels, so pull avoids central tracking of every worker. LeaseTask claims a task atomically; in Postgres use SELECT ... FOR UPDATE SKIP LOCKED, which comfortably handles 50 tasks/s. Move to per-pool Redis or SQS queues at about 10x. A lease lasts about 60 s with a fencing token; workers heartbeat every 15 s. If a worker dies, the reaper requeues the task with attempt+1, and any report with a stale token is rejected. This makes at-least-once execution safe.
State machine. PENDING → QUEUED → LEASED → RUNNING → {PASSED, FAILED, ERROR, TIMED_OUT, CANCELLED}. Run status is an aggregate over tasks. All transitions are conditional updates (WHERE status = expected), so retries of the same message are idempotent.
Failures and retries.
- Infrastructure failures (lost worker, image pull error, node OOM kill): automatic retry with exponential backoff, up to about 3 times, not counted against the test.
- Test failures: retry only if the definition's policy says so (for example two retries for end-to-end). Record every attempt. Fail-then-pass is labelled flaky, never silently reported as a clean pass.
- Timeouts: kill the whole process group, upload partial logs, mark
TIMED_OUT. - Cancellation: mark the run
CANCELLING; workers observe it in the heartbeat response and terminate.
Concurrency and fairness. Check at lease time: per pool (physical capacity), per team (weighted round-robin across team queues so a 10k-shard run cannot starve others), per definition (for example max_concurrent: 1 for a load test on shared staging) and per named resource (semaphores for scarce devices or environments, released on lease expiry).
Scheduling reliability. Run multiple scheduler replicas with a leader lease or row-level locking on next_fire_at. Make fires idempotent with a key of schedule_id + fire_time, so a double fire or a restart after downtime does not duplicate runs. Define a catch-up policy (skip missed fires or run once).
Logs. Workers stream chunks to a log service that fans out to live viewers and flushes to object storage on completion. Viewers fetch the stored object afterwards.
Scaling. Workers autoscale on queue depth per pool. Shard large runs. Partition the result store by day. Rate limit per team at the API. Keep the control plane stateless behind a load balancer.
6. Trade-offs and common mistakes
- Push dispatch gives lower latency but needs worker tracking and back-pressure; pull is simpler and robust to churn.
- Postgres as a queue is simple and transactional but caps out; plan the migration path.
- Common mistakes: mutable definitions that break reproducibility, no fencing token (zombie workers overwrite results), retrying real failures invisibly and hiding flakiness, storing logs or per-case results in the OLTP database, and ignoring fairness so one team monopolizes the fleet.
- Monitoring: queue wait time per pool, lease expiry rate, retry rate by cause, worker utilization, and schedule fire lag, with alerts on each.