Design a Container Job Scheduler and Telemetry Platform
System DesignModel answerLast updated
Design a distributed container execution system featuring resource-constrained scheduling, job lifecycle management, self-fencing node agents, and scalable metric ingestion.
Design a cloud-native platform responsible for scheduling, running, and monitoring batch workloads (containerized jobs) across a large cluster of compute nodes.
Your platform must support multi-tenant job submissions with CPU/memory resource requirements, manage execution lifecycles (retries, timeouts, cancellations), and provide end-to-end metrics collection for both infrastructure health and job performance.
Key Requirements to Address:
- API & Data Representation: Design APIs for workload submission, tracking, and cancellation. Define the persistent data model for jobs, execution attempts, and compute nodes.
- Scheduling Architecture: Explain resource allocation strategies (filtering, scoring, multi-tenant fairness), and handle race conditions during node binding.
- Fault Tolerance & Execution Guarantees: Describe mechanisms for handling node failures, network partitions, job retries (exponential backoff), and double-execution risks.
- Telemetry & Observability Engine: Architect a high-throughput metrics ingestion pipeline for system and workload metrics. Support PromQL-like querying and alert evaluation.
- Security & Isolation: Address multi-tenant CPU/memory isolation and safe cluster operations.
Hints
Hint 1
Distinguish between control plane needs (strong consistency, lower throughput) and metrics telemetry needs (eventual consistency, high ingestion throughput).
Hint 2
Consider how node heartbeats and distributed leases prevent split-brain execution when a worker node loses connectivity.
Hint 3
Address multi-tenant fairness via Dominant Resource Fairness (DRF) or tenant queues rather than simple strict priority.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. System Requirements & Scale Estimates
Functional Requirements
- Workload Lifecycle: Submit containerized batch tasks with requested CPU, RAM, and GPU resources. Support timeouts, retries with backoff, priorities, and cancellations.
- Resource-Aware Scheduling: Evaluate constraints (node labels, taints, capacity) and assign workloads to compute nodes.
- Telemetry & Alerting: Scrape and ingest node and container metrics (CPU, RAM, network, custom app metrics). Provide query and alerting capabilities.
- Multi-Tenancy: Tenant-level quota enforcement, isolation, and fair scheduling.
Capacity & Scale Estimation
- Cluster Scale: 10,000 compute nodes; 500 distinct tenant accounts.
- Job Volume: 1,000,000 job executions per day (~12 jobs/sec steady state, peaking at ~500 jobs/sec during batch bursts).
- Control Plane Write Rate: ~1,000 state-change operations per second during peak execution phases.
- Metrics Ingestion Throughput:
- 10,000 nodes × 500 series/node = 5.0M series.
- 50,000 concurrent jobs × 50 series/job = 2.5M series.
- Total: 7.5M active metric series.
- Scraping interval = 15 seconds → 500,000 samples/second.
- At 16 bytes per sample (timestamp + float value), raw metric bandwidth is 8 MB/s (~64 Mbps), yielding ~700 GB/day of compressed time-series data.
2. API Design
Control Plane APIs (RESTful / gRPC)
POST /v1/jobs
Header: X-Tenant-Id: <tenant_uuid>
Request: {
"name": "etl-processing-job",
"image": "docker.io/org/etl:v1.2",
"command": ["python", "main.py"],
"resources": { "cpu_millis": 2000, "memory_mb": 4096, "gpus": 0 },
"node_selectors": { "disktype": "ssd" },
"priority": 10,
"max_retries": 3,
"timeout_seconds": 3600,
"idempotency_key": "7b2c93d4-1a9e-4a67-b7d1"
}
Response: 202 Accepted { "job_id": "job-89412", "status": "PENDING" }
GET /v1/jobs/{job_id}
Response: 200 OK {
"job_id": "job-89412",
"status": "RUNNING",
"attempts": [
{ "attempt_no": 1, "node_id": "node-44", "state": "FAILED", "exit_code": 137, "reason": "OOMKilled" },
{ "attempt_no": 2, "node_id": "node-12", "state": "RUNNING", "started_at": 1710000100 }
]
}
POST /v1/jobs/{job_id}:cancel
Response: 200 OK { "job_id": "job-89412", "desired_state": "CANCELLED" }
3. Storage & Data Model
We split storage between Strongly Consistent Control Plane State and High-Throughput Time Series Telemetry.
┌────────────────────────┐
│ API Gateway │
└───────────┬────────────┘
│
┌───────────────────────┴───────────────────────┐
▼ ▼
┌───────────────────────┐ ┌───────────────────────┐
│ Job Service │ │ Metrics Ingestion │
└───────────┬───────────┘ └───────────┬───────────┘
│ │
▼ ▼
┌───────────────────────┐ ┌───────────────────────┐
│ Strong State Store │ │ Time Series DB │
│ (CockroachDB / etcd) │ │ (Thanos / Mimir) │
└───────────────────────┘ └───────────────────────┘
Control Plane Schemas (RDBMS or Distributed KV with MVCC/CAS)
jobs
job_id(UUID, Primary Key)tenant_id(UUID, Index)spec_json(JSONB, immutable runtime parameters)state(Enum:PENDING,SCHEDULED,RUNNING,SUCCEEDED,FAILED,CANCELLED)current_attempt(INT)version(INT, used for Optimistic Concurrency Control)not_before(TIMESTAMP, for retries with backoff)
attempts
attempt_id(UUID, PK)job_id(UUID, FK)attempt_number(INT)node_id(STRING)state(Enum:RUNNING,SUCCEEDED,FAILED,LOST)started_at,ended_at(TIMESTAMP)
nodes
node_id(STRING, PK)total_cpu_millis,total_memory_mb(INT)allocated_cpu_millis,allocated_memory_mb(INT)labels(JSONB)lease_expiration(TIMESTAMP)status(Enum:READY,NOT_READY)
4. System Architecture
┌─────────────────────────────────────────┐
│ Control Plane │
│ │
Clients ───────► │ API Gateway ──► Job Service ──► State │
│ Store │
│ Scheduler ◄─────────────────────────┤ │
│ Controller Manager ◄────────────────┘ │
└──────────────────┬──────────────────────┘
│ Direct gRPC
▼
┌─────────────────────────────────────────────┐
│ Worker Nodes │
│ │
│ Node Agent ◄──► Container Engine (cgroups) │
│ │ │
│ └──► Vector / Promtail │
└────────────────────┬────────────────────────┘
│ Push / Scrape
▼
┌─────────────────────────────────────────┐
│ Metrics Engine │
│ │
│ Push Gateway/Collector ──► Kafka │
│ ▼ │
│ Thanos/Mimir ──► Alertmanager/Grafana │
└─────────────────────────────────────────┘
Components
- Job Service: Authenticates incoming REST/gRPC payloads, validates schemas, enforces tenant resource quotas, and writes
PENDINGstates to the Store. - Scheduler: Watches for
PENDINGjobs, runs placement logic, and atomically binds assigned jobs to nodes via Compare-And-Swap (CAS). - Controller Manager: Maintains system reconciliation loops:
- Retry Controller: Re-enqueues failed jobs with backoff.
- Timeout Controller: Cancels execution attempts exceeding limits.
- Node Lifecycle Controller: Monitors agent heartbeats and marks unresponsive nodes
NOT_READY.
- Node Agent (Daemon): Runs on every compute node. Maintains lease heartbeats, manages local container runtimes (runc/containerd), isolates resources using cgroups v2, and enforces local timeouts.
- Observability Pipeline: High-throughput telemetry collector scraping node cgroups and runtime endpoints, buffering through Kafka to a scale-out Time-Series Database (TSDB).
5. Scheduler Architecture & Resource Allocation
┌──────────────────────────────────────┐
│ Scheduler Loop │
└──────────────────┬───────────────────┘
│
▼
┌──────────────────────────────────────┐
│ Priority Queue │
│ (DRF + Tenant Weighted Queues) │
└──────────────────┬───────────────────┘
│
▼
┌──────────────────────────────────────┐
│ Phase 1: Filter (Predicate Check) │
│ - Available CPU / RAM │
│ - Node Selectors / Taints │
└──────────────────┬───────────────────┘
│
▼
┌──────────────────────────────────────┐
│ Phase 2: Score (Node Ranking) │
│ - Bin-packing vs. Spreading │
│ - Node affinity & locality │
└──────────────────┬───────────────────┘
│
▼
┌──────────────────────────────────────┐
│ Phase 3: Optimistic Atomic Binding │
│ (CAS Update on Node Allocations) │
└──────────────────────────────────────┘
Multi-Tenant Queueing & Fairness
The scheduler evaluates jobs using Dominant Resource Fairness (DRF) across tenants, combined with intra-tenant priority queues:
- Tenant Shares: Calculates each tenant's dominant resource share (e.g., CPU percentage vs. Memory percentage of total cluster allocation). Tenants below their fair allocation are prioritized.
- Quota Management: If a tenant exceeds their hard cap, new jobs remain in
PENDINGwithout entering active scheduling evaluation.
Placement Engine (Two-Phase Processing)
Phase 1: Filter (Predicates)
Discards unsuitable nodes based on hard rules:
- $Node_{allocatable} - Node_{allocated} \ge Workload_{requested}$ for both CPU and Memory.
- Label matching (
node_selectors), taints/tolerations, and health status (READY). - At 10,000 nodes scale: To avoid scanning all nodes per job, the scheduler uses feasible node sampling. Once it finds $N$ candidate nodes passing predicates (e.g., 500 nodes or 5% of cluster), it advances to scoring.
Phase 2: Score (Priorities)
Ranks remaining candidates:
- Bin-packing Strategy (Cost-optimization): Maximize resource utilization on active nodes to allow empty nodes to scale down. $$\text{Score} = \left( \frac{\text{Allocated CPU}}{\text{Capacity CPU}} + \frac{\text{Allocated RAM}}{\text{Capacity RAM}} \right) \times 50$$
- Spreading Strategy (High Reliability): Distributes workloads to prevent single node blast radiuses.
Phase 3: Binding (Atomic Commit)
To scale the scheduler horizontally, multiple scheduler instances use Optimistic Concurrency Control:
- Scheduler reads Node allocation state at version $V_1$.
- Computes placement on $Node_A$.
- Executes CAS transaction:
UPDATE nodes SET allocated_cpu = allocated_cpu + req_cpu, allocated_mem = allocated_mem + req_mem, version = version + 1 WHERE node_id = 'node-A' AND version = V1; - If CAS fails due to a concurrent bind, the transaction rolls back, and the job is re-evaluated.
6. Lifecycle Management & Fault Tolerance
[PENDING] ──(Scheduler Bind)──► [SCHEDULED] ──(Agent Ack)──► [RUNNING]
▲ │ │
│ ▼ ▼
(Retry Backoff) (Agent Lost) (Exit 0 / Signal)
│ │ │
├─── [FAILED] ◄────────────────┴─────────────────────────────┼──► [SUCCEEDED]
│ │ │
│ (Retries Exhausted) │
└────────┴───────────────────────────────────────────────────┘
Failure Recovery Scenarios
1. Worker Node Partition & Loss (The Split-Brain Problem)
- Node Lease: Node agents renew a distributed lease (e.g., in etcd or database) every 10 seconds.
- Node Eviction: If no heartbeat is observed for 40 seconds, Node Lifecycle Controller marks node
NOT_READY. - Fencing (Preventing Double-Execution):
- If a node is partitioned from the control plane, its local Agent fails to renew its lease.
- Upon lease expiration, the local Agent automatically sends
SIGKILLto all locally managed containers (Self-Fencing). - Once self-fencing is confirmed by lease expiration, the Controller Manager sets running attempts on that node to
LOSTand reschedules them to healthy nodes.
2. Job Retries & Backoff Logic
- When an execution attempt fails, the retry controller classifies the error:
- Non-retryable: Invalid entrypoint, image pull backoff (
ErrImagePull), application syntax error. Transition state toFAILED. - Retryable: OOMKilled, node failure (
LOST), system SIGKILL, non-zero application exit codes.
- Non-retryable: Invalid entrypoint, image pull backoff (
- Exponential Backoff with Jitter: $$\text{Delay} = \min\left(\text{MaxDelay}, \text{BaseDelay} \times 2^{\text{attempt}} + \text{UniformRandom}(0, \text{Jitter})\right)$$
- Sets
job.not_before = NOW() + Delayand sets job state back toPENDING.
3. Timeouts & Asynchronous Cancellations
- Timeouts: The Node Agent sets a local timer based on
timeout_seconds. If hit, it sendsSIGTERM, waits a grace period (15s), then sendsSIGKILL. The Controller Manager also runs a reconciliation loop checking execution durations as a secondary safety mechanism. - Cancellations: When
POST /v1/jobs/{id}:cancelis invoked:- Control plane updates
job.state = CANCELLEDusing a CAS condition (WHERE state IN ('PENDING', 'SCHEDULED', 'RUNNING')). - Node Agent receives the updated state via watch streams and terminates the local process.
- Control plane updates
7. Metrics Ingestion & Observability Architecture
To isolate telemetry overhead from critical job scheduling:
[ Container cgroups / Exporters ]
│
▼ (Scrape every 15s)
[ Collector Agents ]
│
▼ (Push Batch)
[ Kafka Topic ]
│
┌────────┴────────┐
▼ ▼
[ Thanos / Mimir ] [ Real-Time Alert Engine ]
(TSDB Storage) (PromQL / Threshold Evaluation)
│ │
▼ ▼
[ Grafana ] [ PagerDuty / Webhooks ]
Ingestion Pipeline
- Local Collection: A light metrics agent on each node collects container cgroup stats (
container_cpu_usage_seconds_total,container_memory_working_set_bytes) and node hardware metrics. - Buffering: Metric agents stream compressed batches of samples over gRPC to Apache Kafka. Kafka acts as a write-ahead buffer during downstream storage outages or metric spikes.
- Time Series Store (TSDB): Stream processors consume from Kafka and write to Thanos / Cortex / Grafana Mimir (backed by Object Storage like S3 for long-term retention, with local SSD caching for recent queries).
- Alerting Engine: An Alert Evaluator periodically queries recent metrics using PromQL-like rules (e.g.,
rate(job_failures[5m]) > 0.1) and dispatches notifications via Alertmanager.
8. Multi-Tenancy & Security
- Compute Isolation: Container runtimes enforce Linux namespaces, cgroups v2, and optional
seccomp/AppArmorprofiles to restrict container privileges. Memory limits (memory.max) are strictly enforced by the kernel to prevent cross-tenant OOM impacts. - Data & Control Plane Security:
- API Gateway validates JWT tokens and map requests to authenticated
tenant_idscopes. - Job execution payloads are scoped strictly to isolated tenant network namespaces (CNI network policies).
- Storage tables use Row-Level Security (RLS) indexed by
tenant_idto prevent cross-tenant data access.
9. Key System Trade-offs & Operational Considerations
| Architecture Decision | Selection | Alternative & Trade-off |
|---|---|---|
| Scheduler State Management | Shared State Store with Optimistic Concurrency Control (OCC/CAS) | Single Leader-Elected Scheduler: Simple to reason about, but creates a bottleneck at higher scale (>1,000 binds/sec). |
| Metrics Pipeline Transport | Push via Kafka Buffer to TSDB | Pull-Only Scraping (Standard Prometheus): Pulling 50k ephemeral containers directly leads to target discovery churn and potential loss of metrics when short-lived jobs exit before a scrape cycle. |
| Node Partition Handling | Agent Lease Expiration + Self-Fencing | Aggressive Remote Rescheduling: Rescheduling without strict node fencing risks double-execution if the partitioned node is still alive and running the process. |
10. Summary Checklist for Interview Performance
- Clear separation: Control plane (strong consistency) vs. Telemetry plane (high throughput).
- Correctness mechanisms: CAS transactions on job state transitions prevent races between cancellation, completion, and timeouts.
- Resilience: Node lease self-fencing prevents active-active execution of batch workloads during network splits.
- Fairness: Dominant Resource Fairness ensures multi-tenant equity across dynamic clusters.