Video in progress

In a multi-tenant job scheduler, what queueing algorithm do you choose so that one big customer doesn't block everyone else's queue?

A single shared FIFO or a priority-only queue is unfair: a big tenant takes everything. I use a separate queue per tenant and weighted fair queuing or deficit round robin between them, plus a parallel job limit per tenant. Priority stays inside the tenant.

📖 Answer

One day a single customer submitted 2 million export jobs, and the jobs of the other 400 customers sat in the queue for 6 hours. That's how a global FIFO works.

The options.

Strict priority: the lower queue isn't touched until the higher-priority queue is empty. Starvation is guaranteed, because the low priority may never run at all. I don't use it between tenants.

Round robin over tenants: one from each queue. Simple and fair, but if jobs are of different lengths, a tenant with long jobs gets more resources.

Deficit round robin. Each tenant has a "quota balance". On every cycle a quantum is added to the balance; if the estimated cost of the next job doesn't exceed the balance, it runs and the cost is subtracted. The cost is expected CPU-seconds or the number of rows. It's O(1) per decision.

In weighted fair queuing, each job gets a "virtual finish time": max(tenant_last, global_virtual_time) + cost / weight. A min-heap orders by that time. The weight comes from the plan: a premium tenant 3, a regular one 1. It's O(log T) per decision.

record Job(String tenant, double cost, Runnable task) {}

double start = Math.max(lastFinish.getOrDefault(job.tenant(), 0.0), virtualNow);
double finish = start + job.cost() / weight(job.tenant());
lastFinish.put(job.tenant(), finish);
heap.add(new Scheduled(finish, job));      // PriorityQueue — ordered by finish

What you need beyond the algorithm:

  • a parallel limit: each tenant gets at most K jobs at a time. Fair queuing makes the queue order fair, but one tenant's long jobs can still occupy all the workers;
  • backpressure at admission: a limit on each tenant's queue size, and a 429 once it's exceeded. Even storing 2 million jobs in the queue is a problem;
  • if the cost of a job is unknown, you estimate it with a historical average and correct the balance with the real cost when the job finishes;
  • the p95 wait time in the queue, per tenant. Unfairness shows up on this graph.

Giving each tenant its own Kafka topic doesn't solve this problem: the consumer still has to decide how much to take from which topic. The algorithm gets written somewhere anyway.