Design a Container Job Orchestrator and Observability Platform

Medium · System Design · Software Engineer · Onsite

Prompt

Design a multi-tenant batch container orchestrator and observability service operating over a shared pool of cloud-native compute hosts. Internal engineering teams submit containerized batch workloads—such as hourly ledger reconciliations (ns-ledger), test pipelines, or model-scoring runs—and the platform schedules tasks onto worker machines, tracks execution lifecycles, handles retries and cancellations, and exposes operational telemetry across both jobs and cluster hosts.

Ground your architecture around these core system requirements:

  • Resource-aware multi-tenant scheduling: Submitted jobs declare CPU, RAM, accelerator, and node-pool requirements; placement must honor per-tenant quotas, priority tiers, and machine health without allowing one noisy namespace to starve peers.
  • Fault-tolerant execution lifecycle: Host crashes, transient image-registry blips, runtime timeouts, and user cancellations must transition deterministically without running duplicate concurrent copies during network partitions.
  • Integrated observability and isolation: Job state transitions, queue/execution latencies, per-task resource consumption, and host health must feed dashboards and owner-routed alerts while maintaining strong multi-tenant security boundaries.

Scope & Expectations

  • Submission APIs, state model, and lifecycle management: Asynchronous job submission, inspection, cancellation, and recurring schedule APIs; relational modeling of job intent versus execution attempts; and atomic state-machine transitions across failures, retries, and timeouts.
  • Placement, fairness, and cluster resilience: Fair-share queue ordering, hardware filtering and bin-packing, split-brain fencing on scheduler writes, partition-safe node-loss recovery, and horizontal scaling bottlenecks.
  • Telemetry pipeline and tenant isolation: Capturing workload and node metrics without time-series cardinality explosions, powering dashboards and routed alerts, and enforcing RBAC, quotas, secret injection, and container sandboxing.

Step-by-step walkthrough

  1. Clarify requirements and scope

    A cloud-native job and metrics platform is really two tightly connected systems: a job orchestration system (accept, place, run, retry, and cancel containerized batch jobs) and an observability system (collect metrics, power dashboards, and fire alerts for both jobs and machines). Before drawing architecture boxes, separate the control plane (the central services that store state and make scheduling decisions) from the data plane (the worker machines that actually run user containers).

    Workload assumptions (state clearly and confirm with the interviewer)

    • Users: ~200 internal engineering teams, each isolated in its own namespace with a resource quota.
    • Workload: Short- and medium-lived batch containers (ETL pipelines, CI tests, ML evaluation, report generation) that run from a few seconds to several hours and exit. Long-running stateless web services are out of scope. A job consists of parallelism identical tasks (default 1), where each task runs as one container.
    • Cluster: 1,000 worker nodes across 3 availability zones, each with 64 vCPU and 256 GB RAM, grouped into hardware pools (general, high-mem, gpu).
    • Volume: 1,000,000 tasks per day, requesting an average of 4 vCPU and 16 GB RAM for 10 minutes (600 seconds), with 10x submission spikes at the top of every hour from scheduled (cron) jobs.
    • Priority tiers: prod > batch > best_effort. Higher-priority work can preempt (evict) lower-priority work when the cluster is full.
    • Latency targets: When cluster capacity is available, a task starts within 5 seconds of submission (p99). Job status changes appear in APIs and metrics within 5 seconds. Node health metrics are collected every 15 seconds.

    Functional requirements

    1. Submit, inspect, list, and cancel one-off jobs, plus register recurring cron schedules.
    2. Place tasks onto healthy nodes that satisfy CPU, memory, GPU, node-pool, and availability-zone constraints.
    3. Track every execution attempt and handle failures, retries, cancellations, and timeouts cleanly.
    4. Collect job lifecycle metrics (counts, queue wait, runtime), per-task resource usage, and node health metrics; support dashboards and routed alerts.
    5. Enforce multi-tenant security: per-team quotas, role-based access control, secret injection, network isolation, and container runtime hardening.

    Non-functional requirements

    • Data-plane autonomy: Running containers keep executing even if the control plane goes completely down; only new placements and status updates pause.
    • No duplicate concurrent execution: A task attempt should never run on two nodes at the same time because of a network blip. On node loss, we trade a short wait (~90 seconds) for safety against duplicate execution.
    • High availability: The control plane survives the complete loss of any single availability zone.
    • Headroom to grow: The architecture scales 10x (to 10,000 nodes and 10M tasks/day) without throwing away the core data model or APIs.
  2. Back-of-the-envelope numbers

    To estimate how many tasks run at the same time, we use Little's Law, which states that the average number of active items in a system equals the average arrival rate multiplied by the average time each item spends running.

    Cluster capacity
      1,000 nodes x 64 vCPU    = 64,000 vCPU total
      1,000 nodes x 256 GB RAM = 256,000 GB (256 TB) RAM total
    
    Job volume and database load
      Task arrivals            1,000,000 / 86,400 s = ~11.6 tasks/s avg; ~120 tasks/s at hourly cron spikes
      Concurrent running tasks 11.6 tasks/s x 600 s = ~7,000 tasks running on average (Little's Law)
      Average cluster booking  7,000 x 4 vCPU  = 28,000 vCPU  (~44% of 64,000 vCPU)
                               7,000 x 16 GB   = 112,000 GB   (~44% of 256,000 GB)
      State transitions        ~6 per task (queued, scheduled, running, finished, etc.)
                               -> ~6M transitions/day = ~70 txns/s avg, ~700 txns/s peak
      Job + attempt storage    ~2 KB per task x 1M/day = ~2 GB/day -> ~60 GB for 30 days hot retention
    
    Scheduler throughput
      Peak placement rate      ~120 tasks/s
      In-memory node scan      filtering + scoring 1,000 nodes takes ~0.25 ms in a single thread
                               -> CPU is tiny; database commit latency (~2-5 ms per round trip) is the bottleneck
    
    Metrics volume
      Node health series       1,000 nodes x ~500 metrics/node = 500,000 active time series
      Aggregated job series    200 namespaces x ~25 job names x ~10 metrics = ~50,000 active time series
      TSDB ingest (15 s step)  550,000 series / 15 s = ~37,000 samples/s
      Cardinality trap         if job_id is used as a metric label: 1M tasks/day x 10 metrics
                               = 10,000,000 brand-new time series every single day!
    

    Every major design choice follows directly from these four numbers:

    • ~44% average utilization with 10x hourly bursts means the cluster is comfortable most of the hour, but queues pile up sharply at :00. Fair-share ordering and priority preemption are essential during those bursts.
    • ~0.25 ms in-memory scoring vs. multi-millisecond disk writes means a single active scheduler process can easily place 120+ tasks/s in memory, as long as it batches its database bind writes (for example, committing up to 100 placements in one transaction every 50 ms).
    • ~700 peak transactions/s and ~60 GB of hot records fit comfortably on one relational database primary (PostgreSQL). By contrast, a cluster coordination store like etcd defaults to a 2 GiB total storage cap and would fill up on day one.
    • 10M new time series per day is a monitoring killer. A time-series database (TSDB) indexes every unique combination of metric name and key-value labels in memory; creating millions of short-lived job_id labels (high cardinality) blows up RAM and slows multi-day queries to a crawl. Per-attempt resource charts therefore belong outside the TSDB (covered in Deep dive 3).
  3. Job submission, management, and metrics APIs

    Job submission is asynchronous: POST /v1/jobs validates the request, persists the job as QUEUED, and immediately returns 202 Accepted with a job_id while placement happens in the background. Clients attach an idempotency key—a unique client-generated UUID stored with the job—so if a network timeout causes the client to retry the POST, the server returns the existing job_id instead of launching a duplicate job.

    Job lifecycle (REST over HTTPS)
    POST /v1/jobs                                         Header: Idempotency-Key: <client-uuid>
    {
      "namespace": "ns-ledger",
      "name": "hourly-ledger-reconcile",
      "image": "registry.internal/ledger/reconcile@sha256:4e8a...", // immutable digest, never ":latest"
      "command": ["python", "reconcile.py", "--window", "2026-11-26T09"],
      "resources": { "cpu": 4, "memory_gb": 16, "gpu": 0 },
      "parallelism": 1,
      "priority": "batch",
      "node_pool": "general",
      "timeout_s": 3600,                                  // max runtime per attempt (1 hour)
      "max_queue_s": 21600,                               // fail as Unschedulable after 6 hours waiting
      "retry": { "max_retries": 3, "retry_on_exit_codes": [1, 75] },
      "secrets": ["ledger-db-readonly"],
      "labels": { "domain": "accounting" }
    }
    -> 202 Accepted  { "job_id": "job_01JDX...", "status": "QUEUED" }
    -> 400 invalid spec | 403 unauthorized for namespace | 429 namespace queue cap exceeded
    
    GET  /v1/jobs/{job_id}                                // current status, attempts list, usage summary
    GET  /v1/jobs?namespace=ns-ledger&status=RUNNING&cursor=...
    POST /v1/jobs/{job_id}:cancel                         // idempotent; returns current status
    GET  /v1/jobs/{job_id}/attempts/{attempt_no}/logs?follow=true
    POST /v1/schedules                                    // { "cron": "0 * * * *", "overlap": "forbid", "job": {...} }
    
    Observability APIs
    GET  /v1/metrics/query?expr=...&from=...&to=...&step=15s     // server injects namespace filter automatically
    POST /v1/alert-rules                                  // { "namespace": "ns-ledger", "expr": "...", "for": "10m" }
    

    Three subtle API choices prevent production headaches:

    • Pin images by sha256 digest. If a team pushes a new tag mid-run, retry attempt #2 still runs the exact container bytes as attempt #1.
    • Hold over-quota jobs in QUEUED rather than rejecting them. Teams want batch pipelines to wait smoothly when their quota is busy; only a runaway loop exceeding a generous queue cap (say 50,000 waiting tasks in one namespace) gets 429 Too Many Requests.
    • Make :cancel idempotent. Calling cancel on an already SUCCEEDED or CANCELLED job returns 200 OK with that terminal status rather than throwing an error.
  4. Data model and the task state machine

    Separating intent (jobs) from execution tries (attempts) keeps history clean: when attempt 1 dies because Node 42 lost power, we append attempt 2 rather than overwriting which machine ran attempt 1 or why it failed.

    To guarantee that concurrent actors (for example, a user clicking cancel at the exact millisecond a container exits) never corrupt state, every state change uses compare-and-set (CAS)—an atomic UPDATE ... WHERE status = :expected_status that modifies the row only if nobody else changed it first. In the exact same database transaction, we insert a row into an outbox table (the transactional outbox pattern), which a background relay tails and publishes to an event stream so metrics and notifications never miss a committed state change and never see a rolled-back one.

    Relational schema (PostgreSQL)
    
    jobs        job_id PK (time-sortable UUIDv7), namespace, name, spec JSONB (immutable),
                idempotency_key, priority, status, desired_state ('run' | 'cancel'),
                attempt_count, version, queued_at, finished_at, usage_summary JSONB
                UNIQUE (namespace, idempotency_key)
                INDEX  (status, priority, queued_at)     -- fast recovery of pending queue
                INDEX  (namespace, queued_at DESC)       -- fast team dashboard listing
    
    attempts    (job_id, task_index, attempt_no) PK, node_id, status, reason,
                assigned_at, started_at, finished_at, deadline_at, exit_code,
                cpu_seconds, peak_mem_gb, usage_blob_uri
    
    nodes       node_id PK, pool, zone, labels JSONB, taints JSONB,
                allocatable_cpu, allocatable_mem_gb, allocatable_gpu,
                status ('Ready' | 'NotReady'), cordoned BOOL, lease_expires_at
    
    quotas      namespace PK, max_cpu, max_mem_gb, max_gpu, max_queued_jobs, max_priority
    
    outbox      outbox_id BIGSERIAL PK, aggregate_id, event_type, payload JSONB, created_at
    
    schedules   schedule_id PK, namespace, cron_expr, overlap_policy, job_template JSONB, last_fired_at
    

    Every task attempt moves forward along a strict state machine whose terminal states (SUCCEEDED, FAILED, TIMED_OUT, CANCELLED) can never transition again:

                          bind batch commits                  container starts
           +--> QUEUED -----------------------> SCHEDULED ----------------------> RUNNING
           |      |                                 |                             /  |  \
           |      | > max_queue_s                   | pull 5xx /                 /   |   \ exit 0
    backoff|      v                                 | node lost        retryable/    |    v
    elapsed|    FAILED                              v          +---------------+     |  SUCCEEDED
           | (Unschedulable)                   RETRY_WAIT <----+                     |
           +----------------------------------------+                                | non-retryable or
                                                                                     | retries exhausted
      Cancellation from any non-terminal state:                                      v
        QUEUED / RETRY_WAIT   ----------------> CANCELLED (immediate)             FAILED / TIMED_OUT
        SCHEDULED / RUNNING   -> CANCELLING --> CANCELLED (after agent confirms kill or node is fenced)
    
  5. High-level architecture

      Internal users / CI / Cron controller
                      |
                      v  HTTPS
            +-------------------+        SQL txns (CAS + outbox)       +-------------------------------+
            |  Job & Metrics    |------------------------------------->|  PostgreSQL Job Store         |
            |  API Servers (x6) |<-------------------------------------|  1 primary + 2 sync standbys  |
            +---------+---------+                                      |  across 3 availability zones  |
                      ^                                                +---+-----------+-----------+---+
                      | long-poll watch / status                           |           |           |
                      | (agents talk to API, never DB)              watch  |      CAS  |    outbox | relay
                      |                                                    v           v           v
                      |                                     +----------------+  +-------------+  +--------------+
                      |                                     | Scheduler      |  | Controllers |  | Event Stream |
                      |                                     | 1 active leader|  | - retry     |  | (Kafka/NATS) |
                      |                                     | + 2 standbys   |  | - timeout   |  +------+-------+
                      |                                     | in-mem cache   |  | - node life |         |
                      |                                     +-------+--------+  +-------------+         v
                      |                                             | batched CAS binds        +-----------------+
                      |                                             +------------------------->| Job-Metrics     |
            +---------+----------------------------------------------+                         | Aggregator      |
            |  1,000 Worker Nodes (Data Plane)                       |                         +--------+--------+
            |  Node Agent: runs containers (cgroups/seccomp),        |--- 15 s scrape --->+             |
            |  renews 10 s lease, enforces local timeout,            |                    v             v
            |  buffers live task samples, uploads usage blob on exit |            +-------------------------+
            +---------------------------+----------------------------+            | Sharded TSDB + Alert    |
                                        | compressed usage summary on exit        | Evaluator + Dashboards  |
                                        v                                         +-------------------------+
                                 Object Storage (S3/GCS)
    

    Tracing one job end to end shows how each piece stays decoupled:

    1. Submit: The API server authenticates the caller, checks RBAC and image digest rules, and writes one transaction inserting jobs, attempts (attempt_no = 1, status = 'QUEUED'), and an outbox event.
    2. Schedule: The active scheduler leader learns of the new QUEUED attempt from the change stream, chooses a node in memory, reserves the node's capacity in its in-memory cache immediately, and flushes a batch of CAS bind updates to PostgreSQL every 50 ms.
    3. Execute: The chosen node's agent receives the assignment over its long-poll watch against the API tier, pulls the container image, starts the container inside resource limits, transitions the attempt to RUNNING, and starts a local countdown timer.
    4. Finish: When the process exits, the agent uploads the per-attempt resource trace to object storage and reports the exit code and summary stats. A controller transitions the attempt to SUCCEEDED, RETRY_WAIT, or FAILED.
    5. Observe: The outbox relay streams every state transition to the job-metrics aggregator, which updates exact job counters and queue-wait histograms in the TSDB within seconds.
  6. Deep dive 1: resource-aware placement, fairness, and safe binding

    Step 1 — Order waiting work fairly without O(N log N) sorting. If ns-ledger dumps 100,000 batch jobs into a single FIFO queue, ns-vision's 5 jobs wait for hours. Instead, the scheduler maintains small per-(priority, namespace) FIFO queues in memory and picks the next task using three tie-breakers:

    1. Priority tier: prod before batch before best_effort.
    2. Dominant Resource Fairness (DRF): DRF measures each namespace's current consumption as the largest fraction of any resource quota it uses—max(used_cpu / quota_cpu, used_mem / quota_mem, used_gpu / quota_gpu)—and serves the namespace with the smallest dominant share next. That stops both CPU-heavy and RAM-heavy teams from starving neighbors. prod and batch tasks pause at 100% of their namespace quota; best_effort tasks can borrow idle cluster capacity above quota because they can be evicted at any time.
    3. Submission age: Oldest queued_at wins inside the chosen namespace queue.

    Step 2 — Filter, then score (best-fit packing + soft spread). Placement always checks requested resources, not instantaneous CPU usage, because five quiet containers can spike their memory together and trigger out-of-memory crashes if over-packed. Among feasible nodes, batch workloads benefit from best-fit bin packing: placing a task on the node that leaves the smallest leftover sliver keeps big contiguous holes open on other nodes for 32-vCPU tasks and lets completely empty nodes scale down. Adding +1.0 to the score if the node already runs another task of the same parallel job gently spreads sibling tasks across separate machines.

    Mini-trace: placing a 4 vCPU, 16 GB task from job_74 (node capacity: 64 vCPU, 256 GB)
      Node A (used: 56 vCPU, 224 GB; job_74 absent) -> free after = 4/64 + 16/256 = 0.0625 + 0.0625 = 0.125  <-- WINNER (tightest fit)
      Node B (used: 56 vCPU, 224 GB; job_74 present)-> free after = 0.125 + 1.0 penalty             = 1.125  (avoids stacking job_74)
      Node C (used:  8 vCPU,  32 GB; job_74 absent) -> free after = 52/64 + 208/256 = 0.8125+0.8125 = 1.625  (kept open for big jobs)
    
    from dataclasses import dataclass, field
    
    PRIORITY_RANK = {"prod": 0, "batch": 1, "best_effort": 2}
    
    
    @dataclass
    class NodeState:
        node_id: str
        pool: str
        alloc_cpu: float
        alloc_mem_gb: float
        used_cpu: float = 0.0
        used_mem_gb: float = 0.0
        ready: bool = True
        cordoned: bool = False
        active_jobs: set = field(default_factory=set)
    
    
    @dataclass
    class QueuedTask:
        job_id: str
        namespace: str
        priority: str
        cpu: float
        mem_gb: float
        pool: str
        queued_at: float
    
    
    def namespace_sort_key(task: QueuedTask, ns_usage: dict, ns_quota: dict) -> tuple:
        # Compare priority first, then smallest dominant quota share (DRF), then oldest wait time.
        used_cpu, used_mem = ns_usage.get(task.namespace, (0.0, 0.0))
        quota_cpu, quota_mem = ns_quota[task.namespace]
        dominant_share = max(used_cpu / quota_cpu, used_mem / quota_mem)
        return (PRIORITY_RANK[task.priority], dominant_share, task.queued_at)
    
    
    def node_fits(task: QueuedTask, node: NodeState) -> bool:
        if not node.ready or node.cordoned or node.pool != task.pool:
            return False
        return (
            node.used_cpu + task.cpu <= node.alloc_cpu
            and node.used_mem_gb + task.mem_gb <= node.alloc_mem_gb
        )
    
    
    def pick_best_fit_node(task: QueuedTask, nodes: list[NodeState]) -> NodeState | None:
        best_node = None
        best_score = None
        for node in nodes:
            if not node_fits(task, node):
                continue
            # Fraction of CPU and memory remaining after placing this task (0.0 = exact fit, ~2.0 = empty).
            rem_cpu_frac = (node.alloc_cpu - node.used_cpu - task.cpu) / node.alloc_cpu
            rem_mem_frac = (node.alloc_mem_gb - node.used_mem_gb - task.mem_gb) / node.alloc_mem_gb
            score = rem_cpu_frac + rem_mem_frac
            # Soft anti-affinity: penalize nodes already running another task from the same job.
            if task.job_id in node.active_jobs:
                score += 1.0
            if best_node is None or score < best_score:
                best_node = node
                best_score = score
        return best_node
    

    Step 3 — Prevent split-brain double-booking with a fenced batch transaction. Only one scheduler acts as leader at a time using a leader lease (a time-bounded lock row in PostgreSQL), accompanied by a monotonically increasing integer called a fencing token (scheduler_epoch). What if Leader A freezes during a 15-second garbage-collection pause, Standby B increments scheduler_epoch from 5 to 6, and Leader A wakes up and tries to flush an old batch of placements? Every bind batch locks the epoch row with FOR SHARE:

    Leader A (stale, epoch 5)                       Standby B (taking over -> epoch 6)
    -------------------------                       ----------------------------------
    If B already committed epoch 6:
      SELECT scheduler_epoch ... FOR SHARE -> sees 6 != 5 -> ROLLBACK immediately!
    
    If A is mid-commit when B takes over:
      holds FOR SHARE on leader row --------------> UPDATE leader SET scheduler_epoch = 6 (waits!)
      COMMIT batch                                  unblocks, commits epoch 6, THEN loads fresh DB cache
    

    Because Standby B's UPDATE blocks until any in-flight FOR SHARE batch finishes—and B loads its in-memory node cache after incrementing the epoch—no zombie bind can ever sneak in behind B's back.

    Preemption and head-of-line blocking: - Preemption: When a prod task fits nowhere, the scheduler looks for a single node where evicting lower-priority (best_effort, then batch) tasks frees enough room with the least wasted runtime (youngest victims first). Evicted tasks get SIGTERM -> 30 s grace -> SIGKILL and return to QUEUED with their original queued_at and zero user retries consumed. - Anti-starvation reservation: A 48-vCPU job could starve forever while tiny 4-vCPU tasks keep filling freed slots (head-of-line blocking). Once a task waits past 10 minutes, the scheduler reserves the single node closest to fitting it and stops placing new tasks there until running tasks drain enough room.

  7. Deep dive 2: failures, retries, cancellations, and timeouts

    Node loss without duplicate execution. When a node stops sending heartbeats, the node might actually be dead—or a network switch might have dropped packets between that node and the control plane while its containers keep writing to shared databases. Restarting its tasks immediately would run two live copies at once. We prevent this with a coordinated three-step safety window plus fenced output commits:

    Time since node's last successful lease renewal:
      0 s       10 s       20 s ...   40 s                     60 s                         90 s
      |----------|----------|----------|------------------------|----------------------------|
      Normal renewals every 10 s       Control plane marks      Node agent SELF-FENCES:      Control plane marks
                                       node NotReady (stops     sends SIGKILL to all local   attempts LOST and
                                       placing NEW tasks)       containers immediately       re-queues them
    
    1. Node self-fencing at 60 s: Each node agent measures time on its local monotonic clock from when it sent its last acknowledged lease renewal. At 60 seconds of silence, it immediately kills all local containers with SIGKILL (skipping a 30-second SIGTERM grace period so cleanup finishes well before 90 seconds).
    2. Control-plane wait until 90 s: The node-lifecycle controller waits 90 seconds from when it processed that renewal before moving the node's attempts to RETRY_WAIT. That 30-second gap guarantees local containers are dead before replacements start.
    3. Fenced output commits: For extra safety against a frozen OS kernel, jobs write results to an attempt-scoped path (.../attempt-1/) and call POST /v1/jobs/{id}/attempts/1:commit, which checks attempt_no == current_attempt in PostgreSQL so an old zombie attempt can never overwrite attempt 2's output.

    Classify failures before retrying. Not every non-zero outcome deserves the same reaction:

    Failure reason                 Retry?   Counts against user max_retries?   Backoff policy
    -----------------------------  -------  ---------------------------------  -----------------------------------
    Node lost / node drained       Yes      No (capped at 5 infra retries)     Immediate on a different node
    Preempted by higher priority   Yes      No                                 Immediate, keeps original queued_at
    Image pull 5xx / registry blip Yes      No (capped at 3 infra retries)     30 s, 60 s, 120 s + random jitter
    Image 404 / invalid command    No       -                                  Fail immediately with clear error
    Container OOMKilled (exit 137) Yes      Yes                                Exponential backoff + memory hint
    Exit code in retry_on list     Yes      Yes                                min(10s * 2^(n-1), 10m) + jitter
    Other non-zero exit code       No       -                                  FAILED
    Attempt exceeded timeout_s     No*      Yes (*opt-in retryable)            TIMED_OUT
    

    Adding random jitter (for example, ±25% random delay) stops 500 tasks that failed during the same database hiccup from stampeding back at the exact same millisecond. Capping infrastructure retries at 5 prevents a "poison pill" container that triggers a kernel panic from taking down every node in the cluster one by one.

    Two-layer timeouts and level-triggered reconciliation: - Timeouts: Both the node agent (local timer from container start) and a control-plane timeout controller (scanning deadline_at < now() every 10 s) enforce timeout_s. If the control plane is unreachable, the node still kills runaway code; if the node dies, the control plane still marks the attempt TIMED_OUT. - Level-triggered reconciliation: Message queues drop or delay notifications, so every controller also runs a periodic 30-second sweep comparing desired state in PostgreSQL against actual state reported by nodes—killing orphan containers that have no active attempt and recovering stuck CANCELLING attempts.

  8. Deep dive 3: metrics collection, dashboards, and alerting

    Split bounded fleet metrics from unbounded per-task telemetry. As we saw in the math step, attaching job_id as a TSDB label creates 10M new series every day (cardinality explosion). Instead, we split observability data by cardinality:

    1. Bounded-label series in the TSDB: Node metrics ({node, pool, zone}) and aggregated job metrics ({namespace, job_name, priority, status, reason}) have a small, fixed set of label values (~550,000 active series total), so Prometheus/VictoriaMetrics/M3 queries over 30 days return in milliseconds.
    2. Per-attempt resource traces in agent memory + object storage: While an attempt runs, the node agent samples container CPU, memory, and I/O every 15 seconds into a tiny circular buffer in RAM (served live through the API when a developer opens that job's detail page). When the container exits, the agent writes one compressed JSON/Parquet blob (~4 KB for a 10-minute run) to object storage and saves scalar rollups (cpu_seconds, peak_mem_gb) onto the attempts row in PostgreSQL.

    Derive job counts and latencies from events, not scraping. If a scraper polls active jobs every 15 seconds, a 3-second task that starts and finishes between polls is completely invisible. Instead, the job-metrics aggregator consumes the transactional outbox stream (keeping a short sliding set of seen outbox_ids to deduplicate at-least-once deliveries) and updates exact metrics:

    jobs_finished_total{namespace, job_name, status, reason}   // exact counter of terminal outcomes
    job_queue_wait_seconds_bucket{priority, pool}              // histogram of (assigned_at - queued_at)
    job_run_duration_seconds_bucket{namespace, job_name}       // histogram of (finished_at - started_at)
    scheduler_pending_tasks{priority, pool}                    // live queue depth gauge
    scheduler_oldest_pending_age_seconds{priority, pool}       // starvation detector gauge
    

    Dashboards and owner-routed alerts: - Dashboards: (1) Cluster capacity showing allocatable vs. requested vs. actual usage per pool (highlighting over-requested slack for right-sizing), (2) Scheduler health (queue wait p99, bind latency, preemptions), (3) Namespace view (quota usage, failure breakdown, CPU-hours), and (4) Attempt inspector (timeline, exit reason, live/archived resource chart, streaming logs). - Routed alerts + dead man's switch: Platform alerts (no scheduler leader for 1 min, prod queue wait p99 > 60 s, >5% of a pool NotReady, DB replication lag > 10 s) page the platform SRE team and group correlated node failures into a single alert. Job-level alerts (job_name failure rate > 20%, missed cron schedule, repeated OOMKilled) route to the owning namespace's Slack/PagerDuty. Finally, an external dead man's switch—an independent watchdog outside the cluster that expects a heartbeat metric every minute—pages SRE if the metrics pipeline itself goes silent.

  9. Multi-tenant security and isolation

    Sharing 1,000 machines across 200 engineering teams requires defense in depth so neither buggy scripts nor compromised dependencies can cross team boundaries:

    • Namespace RBAC and server-side query scoping: Every API call authenticates the user or service account via SSO/OIDC and checks namespace permissions. Metrics and log queries inject namespace = <caller_ns> on the server so one team cannot inspect another team's job names or failure rates.
    • Quotas and kernel resource limits: Namespace quotas cap concurrent CPU, RAM, GPU, queued jobs, and max_priority (so every team cannot mark routine jobs prod). On each node, the container runtime configures Linux cgroups (kernel controls that strictly cap CPU shares, RAM, PIDs, and ephemeral disk per container) and seccomp (a kernel filter blocking dangerous system calls like loading kernel modules).
    • Hardened container defaults and supply chain: Admission rejects :latest tags, external registries, unsigned images, privileged: true, host networking, and host filesystem mounts. Containers run as non-root with a read-only root filesystem.
    • Scoped secrets and short-lived workload identity: Secrets are never stored in jobs.spec; the node agent fetches them over mTLS from a secrets manager into an in-memory tmpfs mount only while the assigned attempt runs, alongside a short-lived OIDC token that expires when the attempt ends.
    • Network and sandbox isolation: Default-deny network policies block container-to-container traffic across namespaces. Because standard containers still share the host Linux kernel, workloads executing untrusted external inputs run in a dedicated pool using a sandboxed runtime (gVisor user-space kernel or Kata Containers lightweight microVMs).
  10. Scaling to 10x, fault tolerance, and failure summary

    Surviving zone outages at current scale (1,000 nodes). API servers, controllers, and scrapers run statelessly across 3 availability zones. PostgreSQL runs 1 primary in Zone A and 2 standbys in Zones B and C using quorum synchronous replication (ANY 1 (standby_b, standby_c)): a transaction commits as soon as either standby flushes the write-ahead log to disk. Losing one standby zone never stalls writes, and losing the primary's zone promotes an up-to-date standby with zero lost commits.

    Where the system bends at 10x (10,000 nodes, 10M tasks/day, ~1,200 peak placements/s, ~7,000 peak state txns/s):

    1. Scheduler node scanning: Scoring all 10,000 nodes per task grows 10x slower. Fix: score a random sample of feasible nodes (for example, stop after finding 500 feasible nodes from a rotating cursor—the same percentageOfNodesToScore technique Kubernetes uses), and partition nodes by node_pool so each pool (general, high-mem, gpu) has its own independent scheduler leader.
    2. PostgreSQL write ceiling: ~7,000 state-change transactions/s (plus outbox inserts) pushes a single PostgreSQL primary near its ceiling. Fix: shard jobs, attempts, and outbox horizontally by hash(namespace) across 4–8 PostgreSQL shards (or migrate to a distributed SQL database like CockroachDB/Spanner).
    3. 10,000 node watches: Instead of 10,000 agents polling API servers backed directly by database change feeds, place an in-memory watch fan-out cache tier in front of the store that reads the change stream once and pushes assignments to connected agents by node_id.
    4. 5M node time series: Shard TSDB scrapers by hash(node_id) using consistent hashing and store blocks in a horizontally sharded TSDB backed by object storage.
    Failure scenario                    Impact                               Automated recovery
    ----------------------------------  -----------------------------------  -------------------------------------------------
    Node crashes or loses power         Running tasks on that node stop      40 s -> NotReady; 90 s -> attempts re-queued elsewhere
    Network partition (node isolated)   Control plane sees missed leases     Agent self-fences (SIGKILL) at 60 s; fenced commits block duplicates
    Active scheduler leader crashes     New placements pause briefly         Warm standby acquires lease (~10-15 s), loads DB state, resumes
    Zombie scheduler wakes from pause   Tries to flush stale bind batch      Epoch check under FOR SHARE fails; transaction rolls back
    PostgreSQL primary zone goes down   Writes fail for ~15-30 s             Promote sync standby (0 data loss); clients retry with Idempotency-Key
    Internal image registry 5xx         New containers cannot pull images    Retry pull with backoff without burning user's max_retries; page SRE
    Metrics TSDB outage                 Dashboards freeze                    Running and new jobs unaffected; external dead man's switch pages SRE
    Cancel races with exit code 0       Both try to update attempt status    CAS update ensures first commit wins; terminal state never flips
    

Intuition & how it works

Think of this platform like an airport ground-control tower paired with a flight-data recorder. Engineering teams (airlines) submit containerized batch jobs (flight plans) specifying how much CPU, memory, and GPU they need (aircraft size). One active scheduler leader (the head air-traffic controller) keeps a fast in-memory map of all 1,000 worker nodes (gates), picks the tightest-fitting healthy node for the next fair-share job, and commits batches of assignments to PostgreSQL. Meanwhile, a local agent on each worker node (the tarmac crew) runs the containers, enforces time and memory limits locally, and keeps existing containers running smoothly even if radio contact with the control tower temporarily drops. For observability, instead of opening a permanent telemetry channel per short-lived task in the monitoring database, the flight-data recorder counts exact lifecycle events from a state-change stream and archives each finished attempt's detailed resource chart as a tiny file in object storage.

A naive design usually fails in three places at once: it puts all submitted jobs into a single first-in-first-out queue, restarts tasks the instant a worker node misses a heartbeat, and labels every container metric in a time-series database (TSDB)—a database optimized for timestamped numbers indexed by key-value tags—with job_id. Under real traffic, one team submitting 100,000 batch jobs starves every other team for hours, a 30-second network glitch causes two copies of the same task to overwrite shared output, and 1,000,000 daily jobs create 10,000,000 brand-new job_id metric series every day (high cardinality) until the TSDB runs out of memory.

Walk through a tiny concrete trace with 2 nodes (Node-1 with 8 vCPU free, Node-2 with 32 vCPU free) and 3 submitted tasks:

  1. Fair queue ordering: ns-ledger is already using 80% of its CPU quota and has 500 tasks waiting; ns-vision is using 10% of its quota and submits job_74 needing 8 vCPU. Using Dominant Resource Fairness (DRF)—ranking teams by whichever resource (CPU, memory, or GPU) represents the largest fraction of their quota—the scheduler picks ns-vision's job_74 ahead of ns-ledger's backlog.
  2. Best-fit placement and batched binding: Both Node-1 (8 vCPU free) and Node-2 (32 vCPU free) fit job_74. Best-fit scoring picks Node-1 (0 vCPU left over) so Node-2's contiguous 32-vCPU block stays open for large jobs, then commits attempt 1 -> SCHEDULED to PostgreSQL using compare-and-set (CAS)—an atomic update that succeeds only if the attempt is still QUEUED—alongside an event row in an outbox table written in the same transaction.
  3. Execution and partition-safe recovery: Node-1's agent sees the assignment, starts the container (RUNNING), and renews its lease (a short-lived heartbeat timestamp) every 10 seconds. Suppose Node-1's network cable is unplugged: at 40 seconds the control plane marks Node-1 NotReady; at 60 seconds Node-1's agent self-fences by sending SIGKILL to its own containers; only at 90 seconds does the control plane create attempt 2 (QUEUED) for Node-2 without consuming ns-vision's user retry budget.
  4. Metrics without series bloat: When attempt 2 exits with code 0 on Node-2, its agent uploads the 15-second CPU/memory trace to object storage, updates SUCCEEDED in PostgreSQL, and the outbox event increments jobs_finished_total{namespace="ns-vision", status="SUCCEEDED"} in the TSDB.

Key trade-offs

  • Single active scheduler leader vs. distributed multi-scheduler. One leader holding a complete in-memory snapshot of 1,000 nodes makes globally optimal decisions for DRF fairness, best-fit packing, and priority preemption in ~0.25 ms per task, using batched commits and a fencing token (a monotonically increasing leader epoch number checked under a database lock) to prevent split-brain writes. Multiple concurrent schedulers scale past 10,000 nodes, but introduce placement conflicts or require partitioning the cluster into isolated pools with slightly weaker global fairness.
  • Best-fit bin packing vs. even spreading. Best-fit packs tasks onto already-busy nodes so large contiguous holes remain available for huge jobs and empty nodes can be terminated to save cloud cost. Spreading minimizes how many tasks fail when one machine dies. For batch containers, best-fit wins overall, paired with a soft score penalty that spreads tasks belonging to the same parallel job across different nodes.
  • Scheduling on requested resources vs. measured usage. Placing containers by their declared CPU/memory requests leaves idle slack when teams overestimate, which we surface on right-sizing dashboards, but prevents sudden out-of-memory cascades when several containers spike together. Overcommitting unused slack is restricted strictly to best_effort tasks, giving the node a clear, lossless eviction order.
  • Waiting 90 seconds on node loss vs. instant rescheduling. Re-queuing tasks after 20 seconds of missed heartbeats lowers recovery latency when hardware dies, but risks running duplicate containers during a transient network split. Waiting 90 seconds while the isolated agent self-kills at 60 seconds—backed up by attempt-checked output commits—trades ~90 seconds of recovery delay for strong protection against duplicate side effects.
  • Reason-aware retry policy vs. flat max_retries counter. Classifying failures into infrastructure faults (node loss, preemption, registry 5xx) versus workload faults (OOMKilled, non-zero exit code, missing image) requires extra reporting logic in the agent, but avoids wasting 3 retries on a typo in an image name and avoids penalizing users when the platform preempts their job.
  • Event-driven job metrics + object-storage usage blobs vs. scraping everything into the TSDB. Computing job counters and queue-wait histograms from the transactional outbox stream captures 2-second tasks that periodic scraping misses, while storing per-attempt CPU/memory charts in object storage avoids 10M new job_id TSDB series per day. The trade-off is maintaining two read paths (TSDB for fleet/team aggregates, object storage + agent buffer for individual attempt charts).
  • Shared Linux kernel containers vs. microVM sandboxes. Standard containers isolated with Linux cgroups (resource caps) and seccomp (system-call filtering) maximize density and start in milliseconds, whereas dedicated pools or microVM sandboxes (Kata Containers, gVisor) add memory overhead and startup latency in exchange for stronger protection against kernel vulnerabilities.

Common mistakes

  • Using etcd or ZooKeeper as the primary job database. Coordination stores hold cluster leases and small configuration metadata well, but their multi-gigabyte storage limits collapse under millions of historical job and attempt rows.
  • Putting job_id or attempt_id into TSDB metric labels. Unbounded identifier labels cause high-cardinality index bloat that exhausts TSDB memory within days.
  • Using a single global FIFO queue without per-tenant fairness. Without DRF or per-namespace round-robin, one team's 100,000-task backfill blocks urgent batch pipelines across the entire company.
  • Rescheduling tasks immediately when heartbeats stop, with no fencing. A network partition leaves old containers running blindly alongside newly scheduled replacements, corrupting downstream tables or files.
  • Treating all failures identically. Counting priority preemption against a user's max_retries causes innocent jobs to fail permanently during busy hours, while retrying ImageNotFound wastes queue slots.
  • Enforcing timeouts in only one place. Control-plane-only timeouts fail to stop runaway containers during a control-plane outage; node-only timeouts leave attempts stuck RUNNING forever in the database if the node crashes.
  • Updating job state without compare-and-set (WHERE status = :expected). A cancellation racing with container exit can overwrite SUCCEEDED with CANCELLED or leave orphan containers running.
  • Paging platform SREs on user code crashes, or lacking an external dead man's switch. Alert fatigue hides real outages, and a broken metrics pipeline cannot fire an alert about itself unless an external watchdog monitors its heartbeat.

Follow-up questions

  • How would you extend the scheduler to support gang scheduling, where an 8-GPU distributed training job must launch all tasks simultaneously or wait? Annotate the job spec with min_available = 8 so the scheduler evaluates all 8 tasks atomically inside its in-memory node snapshot: it tentatively reserves slots for all 8 (preferring co-location within one rack or zone for high-bandwidth interconnects) and commits all 8 SCHEDULED transitions inside one PostgreSQL transaction, or rolls back every tentative reservation if task #8 cannot fit so GPUs never deadlock holding partial gangs. Because single-GPU jobs would otherwise starve an 8-GPU gang, once a gang waits past a starvation threshold (e.g., 5 minutes), the scheduler pins target GPU hosts and only backfills short tasks whose timeout_s finishes before the gang's projected launch window. If any member fails mid-training, a controller cancels sibling tasks and restarts the full gang from its latest saved checkpoint.
  • Suppose a runaway client script submits 200,000 batch jobs from a single tenant within two minutes. How does the platform shield other teams? First, per-namespace API rate limiters and a hard pending-queue ceiling (such as 50,000 QUEUED tasks per namespace) reject overflow submissions at the API tier with 429 Too Many Requests and a Retry-After header before they flood PostgreSQL. Second, across the 50,000 tasks that entered the queue, DRF ordering guarantees that once the noisy namespace reaches its quota share, newly arriving tasks from any peer namespace bypass all 49,900 remaining tasks in O(namespaces) time. Third, during off-peak hours, surplus tasks marked best_effort may borrow idle cluster capacity and be preempted within seconds as soon as another tenant submits work.
  • Which architectural bottlenecks emerge first if cluster scale grows 20x to 20,000 worker nodes and 20 million daily tasks, and how would you re-architect them? Peak state updates climb to ~14,000 transactions/s and host telemetry reaches ~10,000,000 active time series. First, partition scheduling across node_pool and availability zone so each scheduler leader manages ~2,000–3,000 nodes and scores a bounded random sample of feasible nodes per task, exchanging namespace usage summaries every couple of seconds through a lightweight quota-aggregation service so DRF remains nearly global. Second, shard PostgreSQL (jobs, attempts, outbox) by hash(namespace) across multiple primaries (or adopt distributed SQL) and place an in-memory watch fan-out tier ahead of the database so 20,000 node agents do not tail DB change streams directly. Finally, shard TSDB scrapers and storage blocks horizontally by hash(node_id) while object storage absorbs the 20M daily per-attempt resource blobs effortlessly.

Follow-up questions

Similar questions

More Palo Alto Networks interview questions

All 9 Palo Alto Networks questions →