Designing a Scalable Mixed-Latency Multi-Tenant Workflow Engine
System DesignModel answerLast updated
Architect a multi-tenant orchestration engine handling high-throughput fast I/O tasks alongside long-running LLM tasks with tenant fairness and tiered state storage.
Design an enterprise-grade, multi-tenant workflow orchestration platform capable of executing Directed Acyclic Graphs (DAGs) containing two distinct categories of tasks: short fast I/O tasks (e.g., API calls, DB reads) and long-running generative AI / LLM tasks.
System Specifications & Parameters
| Metric / Parameter | Value |
|---|---|
| Total Registered Workflow Definitions | 10 million |
| Active Workflow Executions (Runs) | ~1 million / day |
| Average Graph Composition | 10 tasks total (8 Fast I/O, 2 Slow LLM) |
| Stated Daily Task Execution Volume | ~100 million tasks / day |
| Peak Global Task Dispatch Rate | 5,000 – 10,000 tasks / second |
| Fast I/O Task Execution Latency | 10 ms – 50 ms |
| Slow LLM Task Execution Latency | 10 s – 60 s |
| Daily Intermediate Data & File Artifacts | ~200 TB / day |
| State Transition Audit Logs | ~100 million records (~200 GB) / day |
Note on Discrepancies: The total runs per day ($1\text{M}$) times average tasks per run ($10$) yields $10\text{M}$ tasks/day, whereas the separate metric reports $100\text{M}$ tasks/day. Treat this discrepancy as an intentional data ambiguity to address during capacity planning.
Key Requirements
Part 1: Capacity Sizing & Latency-Aware Task Dispatching
- Reconcile the discrepancy in task execution volume estimates and calculate average vs. peak throughput requirements.
- Calculate total concurrent execution slots required for both Fast I/O and Slow LLM tasks under peak load.
- Design an execution queue and worker isolation model that ensures slow, blocking LLM calls never starve fast I/O tasks.
Part 2: State Persistence, Storage Tiering & Artifact Management
- Design the storage architecture for workflow definitions, active run state transitions, append-only execution logs, and large task artifacts.
- Propose schema models, primary/partition keys, and query patterns that allow low-latency execution state checks without scanning historical logs or retrieving heavy payloads.
Part 3: Multi-Tenant Isolation & Fair Scheduling
- Architect fairness mechanisms to handle bursty multi-tenant submissions (e.g., a single tenant enqueuing 500,000 workflows simultaneously).
- Prevent downstream rate-limiting (e.g., LLM vendor token limits) while maintaining high overall system utilization through capacity borrowing.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
System Architecture Overview
+-----------------------------------+
| API Gateway & Rate |
| Limiter / Ingestion |
+-----------------+-----------------+
|
v
+-----------------+-----------------+
| Workflow Orchestrator |
| (DAG Parser & State Engine) |
+-------+-------------------+-------+
| |
Fast Tasks Queue | | Slow LLM Queue
(e.g., Kafka/SQS) v v (e.g., Kafka/SQS)
+-------+-------+ +-------+-------+
| Fast Task Q | | LLM Task Q |
+-------+-------+ +-------+-------+
| |
v v
+-------+-------+ +-------+-------+
| Fast Worker | | LLM Worker |
| Pool (I/O) | | Pool (Async) |
+-------+-------+ +-------+-------+
| |
+----------------------------+-------------------+----------------------------+
| | |
v v v
+---+-------------------+ +---------+-----------+ +---------+-----------+
| Operational State DB | | Historical Logs DB | | Object Storage |
| (Redis/DynamoDB) | | (ClickHouse/S3) | | (S3/GCS) |
| Active States & Locks | | Audit Traversal | | Artifacts & Payloads|
+-----------------------+ +---------------------+ +---------------------+
Part 1 — Capacity Sizing & Latency-Aware Task Dispatching
1. Reconciling the Data Discrepancy
- Calculation A ($1\text{M}$ runs/day $\times 10$ tasks/run): $10\text{M}$ tasks/day.
- Average dispatch rate = $10\text{M} / 86,400 \approx 116\text{ tasks/sec}$.
- Calculation B (Stated task volume): $100\text{M}$ tasks/day.
- Average dispatch rate = $100\text{M} / 86,400 \approx 1,157\text{ tasks/sec}$.
- Peak Requirement: $5,000 \text{ to } 10,000 \text{ tasks/sec}$.
Root Cause Analysis for Discrepancy:
- Task Retries & Attempts: 1 workflow task may experience multiple execution attempts due to transient network failures or rate limits (e.g., $10\text{M}$ logical tasks executing $\sim 100\text{M}$ attempts under high failure/retry policies).
- Dynamic Loops & Child Workflows: Workflows contain dynamic branching or
for-eachloops expanding at runtime beyond static workflow definitions. - Internal Control Tasks: State evaluations, timers, and callback handshakes counted as execution events.
Architectural Baseline: We size system queues and execution pools for the stated peak dispatch rate of 10,000 tasks/sec, maintaining safety margins for high retry rates.
2. Concurrency Calculations (Little's Law: $L = \lambda \times W$)
Assume task distribution at peak ($10,000 \text{ tasks/sec}$):
- Fast I/O Tasks (80%): $8,000 \text{ tasks/sec}$, average duration $W_{\text{fast}} = 30\text{ ms} = 0.03\text{ s}$.
- Slow LLM Tasks (20%): $2,000 \text{ tasks/sec}$, average duration $W_{\text{slow}} = 35\text{ s}$.
In-Flight Concurrency Requirements ($L$):
- Fast I/O Tasks: $L_{\text{fast}} = 8,000 \times 0.03 = 240 \text{ concurrent tasks}$.
- Slow LLM Tasks: $L_{\text{slow}} = 2,000 \times 35 = 70,000 \text{ concurrent tasks}$.
Key Insight: Despite accounting for only 20% of throughput, LLM tasks dominate concurrent execution slots by a factor of $\sim 290\times$ ($70,000$ vs $240$). Unmanaged unified pools would quickly saturate with blocking LLM tasks, completely stalling fast I/O processing.
3. Worker Isolation & Queueing Architecture
+-----------------------+
| Incoming Task Dispatch|
+-----------+-----------+
|
+-------------+-------------+
| Task Classification Node |
+-------------+-------------+
|
+----------------------+----------------------+
| Fast Task | Slow LLM Task
v v
+-----------------------+ +-----------------------+
| Fast I/O Task Queue | | LLM Task Queue |
| (Priority Partition) | | (Tenant Priority Q) |
+-----------+-----------+ +-----------+-----------+
| |
v v
+-----------------------+ +-----------------------+
| Non-blocking Worker | | Async Event-Driven |
| Pool (Epoll/Netty) | | Polling / Webhook Pods|
| Sized for ~500 Concur | | Sized for ~100k Concur|
+-----------------------+ +-----------------------+
-
Queue Segmentation:
- Separate broker queues (e.g., Apache Kafka topics or SQS queues) for
fast-io-tasksandllm-tasks. - Priority queues embedded within each topic ordered by tenant weight and submit time.
- Separate broker queues (e.g., Apache Kafka topics or SQS queues) for
-
Worker Pool Specialization:
- Fast Worker Pool: Lightweight non-blocking event loops (Node.js/Go/Rust epoll-based). Optimized for low CPU and low memory overhead per task. Dedicated pool size: ~500 execution threads/coroutines.
- Slow LLM Worker Pool: Asynchronous event-driven orchestrator workers using a De-coupled Invocation-Status Pattern:
- Worker issues API request to LLM provider (or self-hosted engine).
- Worker persists request metadata & callback registration, then frees thread slot immediately.
- Callback/Webhook receiver captures responses or a poller picks up state, restoring workflow execution.
- This prevents keeping 70,000 OS threads or heavy worker containers idle during token generation.
Part 2 — State Persistence, Storage Tiering & Artifact Management
1. Multi-Tiered Storage Architecture
| Data Type | Daily Volume | Tier | Technology Choice | SLA / Pattern |
|---|---|---|---|---|
| Workflow Definitions | Static ($10\text{M}$ total) | Master Metadata | PostgreSQL / CockroachDB | Read-heavy, ACID, cached in Redis |
| Live Execution State | Hot mutated state | State Store | Redis / DynamoDB | Ultra-low latency ($< 5\text{ ms}$ reads/writes) |
| History / Audit Logs | ~200 GB / day ($100\text{M}$ recs) | Append-Only Log | ClickHouse / Cassandra | Write-heavy, range queries by run_id |
| Intermediate Payloads | ~200 TB / day | Blob / Object Store | AWS S3 / MinIO | Pre-signed URL passing, non-database |
2. Schema Models & Access Patterns
A. Active Run State (Operational Database - DynamoDB / Key-Value)
- Partition Key:
run_id(UUID) - Sort Key:
METADATA - Payload Attributes:
workflow_id,version,tenant_id,status(RUNNING, FAILED, COMPLETED),completed_tasks(Bitset/List),pending_dependency_graph,created_at,updated_at. - Pattern: Fast conditional updates (Optimistic Locking via CAS) when a task finishes to determine next runnable node in DAG.
B. Append-Only Execution Log (ClickHouse Log Store)
- Primary Key:
(tenant_id, workflow_id, run_id, task_id, timestamp)
CREATE TABLE task_execution_logs (
tenant_id UUID,
run_id UUID,
task_id VARCHAR(64),
attempt_number UInt8,
execution_host VARCHAR(64),
status Enum8('PENDING'=1, 'RUNNING'=2, 'SUCCESS'=3, 'FAILED'=4),
error_code LowCardinality(String),
payload_s3_uri String,
started_at DateTime64(3),
finished_at DateTime64(3)
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(started_at)
ORDER BY (tenant_id, run_id, task_id, attempt_number);
C. Payload Storage & Reference Passing
- Large task intermediate outputs (images, vectors, large text contexts) never pass through the database or broker queues.
- Fast tasks write outputs to Object Storage (
s3://workflows/payloads/{tenant_id}/{run_id}/{task_id}.bin). - Workers emit completion events containing lightweight references:
{"run_id": "...", "task_id": "step_2", "output_ref": "s3://..."}.
Part 3 — Multi-Tenant Isolation & Fair Scheduling
1. Multi-Layer Admission & Concurrency Throttling
When a bursty tenant enqueues 500,000 runs simultaneously:
Incoming Requests -> Tenant Rate Limiter (Token Bucket)
|
v
Global Submission Queue
|
+-------------+-------------+
| Weighted Fair Queue (WFQ) |
+-------------+-------------+
|
+---------------+---------------+
| |
Tenant A (Weight 1) Tenant B (Weight 4)
[Max 1,000 Active Slots] [Max 4,000 Active Slots]
| |
v v
Active Worker Execution Active Worker Execution
-
Submission Layer Limiter (Token Bucket per Tenant):
- Soft-cap API submissions to protect DAG ingestion nodes. Submissions exceeding limits receive HTTP 429 backpressure responses or are buffered into tenant-specific cold staging queues.
-
Weighted Fair Queueing (WFQ) Scheduler:
- Active execution slots for each task queue (
fast-ioandllm) managed via Weighted Fair Queueing across tenants based on subscription tier. - Dynamic dynamic slot allocation: $$\text{Tenant Slot Share} = \min\left(\text{Tenant Limit}, \frac{\text{Tenant Weight}}{\sum \text{Active Tenant Weights}} \times \text{Total Capacity}\right)$$
- Active execution slots for each task queue (
-
Downstream Resource Rate-Limiting (LLM Quota Protection):
- Multi-tenant shared token bucket configured per upstream provider (e.g., OpenAI API rate limits: $100\text{k}$ TPM, $10,000$ RPM).
- Global rate limiter (Redis-backed token bucket or Governor process) controls token acquisition prior to popping LLM tasks off queue.
2. Capacity Borrowing Framework
- Unused tenant allocation is made available to background backfills or bursty tenants via Preemptible Slot Pools.
- If Tenant A has a capacity limit of 2,000 tasks but uses only 200, Tenant B can borrow the remaining 1,800 slots.
- Preemption Rule: If Tenant A submits work, Tenant B's borrowed Fast I/O tasks finish within 50ms (draining naturally). Borrowed LLM tasks are not abruptly killed; instead, Tenant A receives priority for newly freed slots until the target ratio is re-established.
3. Operational Metrics & Starvation Monitoring
To detect multi-tenant starvation and system degradation:
- Scheduling Lag (Per Tenant & Class): $\Delta t = t_{\text{dispatch_start}} - t_{\text{enqueued}}$. High lag on Fast Tasks indicates thread pool saturation.
- Tenant Occupancy Ratio: $\frac{\text{Active Slots Used by Tenant } X}{\text{Total Available Slots}}$.
- Queue Depth vs. Active Processing Ratio: Pinpoints when downstream rate limits (e.g., LLM 429s) back up queues despite available internal worker CPU.
- Preemption Eviction Rate: Tracks how often capacity borrowing creates schedule jitter for low-priority tiers.
Key System Trade-offs & Summary
| Architecture Decision | Chosen Strategy | Alternative | Trade-off Rationale |
|---|---|---|---|
| Task Model | Decoupled Async Event Invocation for LLM | Persistent Thread-Per-Task | Saves tens of thousands of idle OS threads/connections during long model generations. |
| Operational State DB | Key-Value Store with Optimistic Locking | Relational DB with Row Locking | Avoids lock contention under 10k/sec dispatch across concurrent DAG nodes. |
| Payload Transfer | S3 Storage + URI References | Direct Payload in Queue Messages | Prevents queue broker bloat and memory pressure; keeps state messages under 2 KB. |
| Tenant Fairness | Weighted Fair Queueing + Borrowing | Strict Static Partitioning | Maximizes global resource utilization while providing soft isolation guarantees. |