TL;DR
- Split latency-sensitive work from bulk jobs first. Set a pool-wide execution limit and separate per-tenant limits for concurrency and admission.
- Schedule among tenants with runnable work and available capacity. A shared FIFO queue or broker delivery order cannot enforce a per-tenant concurrency cap.
- Make each claim a short transaction with a lease and an attempt identifier. Release capacity on completion, and reclaim expired leases without making side effects repeat.
- Scale individual worker pools on service time and eligible queue age. Keep dashboards for quiet tenants and workloads whose capacity is already capped.
How a single tenant consumes a shared worker pool
A customer starts a 500,000-record CSV import. The application publishes thousands of jobs to the same pool that processes notifications and sends billing updates. Queued jobs from other tenants now compete with a long backlog and several workers are already busy waiting on imports. Upgrading workers can increase total throughput while leaving the next small notification behind the same scheduling bottleneck.
The largest tenant may be noisy when each job takes longer to finish. A thousand 20-millisecond jobs need about 20 seconds of worker time in aggregate. Ten 30-second jobs need 300 seconds. Both workloads can saturate the same pool in different ways. Counting queue depth without measuring running time makes them look backwards, and a per-tenant requests-per-minute limit overlooks how long a small number of jobs can hold resources.
Define the target for each workload class before choosing an algorithm. For delivery notifications, the meaningful interval could be job created to dispatch started. For imports, a user may care about time to the first confirmed chunk and eventual completion, with partial progress visible. Billing and webhooks may have external rate limits and a stricter retry budget. A single queue age percentile obscures those distinct expectations.
Follow the shared dependencies as well as the queue. Separate bulk and interactive workers can still compete for database connections, object storage bandwidth, or vendor API quotas. Reserve independent connection budgets and place global limits around each constrained service. Otherwise, the queue stays healthy while every interactive job waits on the shared database.
Separate admission, fairness, and execution limits
Use workload pools to protect latency-sensitive jobs
Put imports, exports, and enrichment into a bulk pool. Give short user-facing notifications a separately sized pool. Use a dedicated class for work whose downstream limits differ substantially, such as a payment provider. Start with a small number of classes aligned to service objectives and bottlenecks. Giving every job type its own queue fragments capacity and makes incident response and retry policies hard to compare. Celery guidance for routing and optimizing workers
Chunk expensive jobs at natural restart boundaries. For an import, the user-facing job tracks progress while workers process stable chunks. The chunk units need to be bounded by expected cost, with record count as one input. A batch of rows with remote lookups costs more than a batch with local validation. Persist outcomes by chunk or stable operation key so a retry observes what it already completed. Put a ceiling on chunk fan-out per tenant before publishing work to the shared system.
Limit queued work and running work separately
Admission answers whether more work can enter the system. Concurrency answers how many attempts may run at once. A token bucket or an outstanding-job limit controls admission. A lease or slot controls active execution. Without admission limits, a tenant with capped execution can still fill the backlog with millions of jobs that will take days to drain. Without execution limits, that same tenant can briefly consume all available workers when its burst is accepted.
Use authenticated tenant identity when producing work. Allow plans or workload policies to choose the cap and admit based on the logical tenant and class. Never infer isolation from an arbitrary tenant label inside client-supplied messages. For retrying tasks, count each attempt against executing capacity, and measure failures by original job as well so a retry loop cannot hide an accumulation of unfinished work.
Choose a fairness rule you can explain during an incident
A worker scheduler can pick the eligible tenant last dispatched longest ago, then take its oldest ready job. This approximates round-robin across active tenants without maintaining one queue object per tenant. It assumes job chunks in the class cost roughly the same. For varied prices or explicit plan weights, weighted or deficit scheduling gives each tenant service credit and debits an estimated work cost per dispatch. Cost estimates need calibration from actual runtime and should be bounded so inaccurate estimates do not starve jobs indefinitely.
All eligible tenants may be idle except one. A work-conserving policy can use spare capacity when a workload allows opportunistic execution, but the cap is then a reserved-share policy with a burst ceiling. Call ceilings and guarantees what they are. If a downstream vendor enforces a hard concurrency limit, preserve the hard cap even when all other tenants are quiet.
Implement lease-based dispatch in PostgreSQL
Represent quota as durable slots
Use one tenant_dispatch row per workload class and tenant. Give it a monotonically increasing last_ticket and create as many tenant_slot records as the tenant is allowed to occupy in that class. Use unique keys for both records. A slot stores the claimed job, a lease expiry, and an attempt token. Mark slots that are being reduced out of the pool as disabled for future claims, then allow existing attempts to finish. Add a partial queue index on (lane, tenant_id, available_at, id) WHERE state = 'queued'.
For clarity, this example uses PostgreSQL's default Read Committed mode and keeps claims, completion, and reclamation in short transactions. Every path changing slots or job ownership first locks the matching tenant_dispatch row. The job's actual workload runs after commit. Treat lock order as part of the scheduler contract so a completion cannot deadlock with a reclaim that touches the same rows in another order.
-- Start one Read Committed transaction. $1 is the selected lane.
SELECT d.tenant_id
FROM tenant_dispatch AS d
WHERE d.lane = $1
AND EXISTS (
SELECT 1 FROM tenant_slot AS s
WHERE (s.lane, s.tenant_id) = (d.lane, d.tenant_id)
AND s.enabled AND s.job_id IS NULL
)
AND EXISTS (
SELECT 1 FROM worker_job AS j
WHERE (j.lane, j.tenant_id) = (d.lane, d.tenant_id)
AND j.state = 'queued'
AND j.available_at <= statement_timestamp()
)
ORDER BY d.last_ticket, d.tenant_id
LIMIT 1
FOR UPDATE OF d SKIP LOCKED;
Order selection by tickets from a database sequence and move the chosen tenant to the back on every committed claim. Concurrent claimers can skip a row currently being updated, so the schedule is approximate. PostgreSQL documents that SKIP LOCKED offers an inconsistent view appropriate for queue consumers. If no tenant is selected, commit without claiming and wait using bounded polling with jitter or a notification hint. A notification should only wake consumers. The durable queue determines whether work exists. PostgreSQL locking clauses
Confirm a free slot and a ready job under the lock
The worker still holds the tenant dispatch row lock. Re-read the ready job and the open slot in the transaction, as those checks happened before the tenant was locked. This statement does both reads, claims the job, binds its attempt to the slot, and moves the tenant to the back. It assumes the slot primary key is (lane, tenant_id, slot_no), job IDs are globally unique, and worker_attempt_seq and worker_dispatch_seq are created PostgreSQL sequences.
-- Same transaction, next statement. $1 = lane, $2 = locked tenant ID.
WITH free_slot AS (
SELECT lane, tenant_id, slot_no
FROM tenant_slot
WHERE lane = $1 AND tenant_id = $2 AND enabled AND job_id IS NULL
ORDER BY slot_no
LIMIT 1
), next_job AS (
SELECT id
FROM worker_job
WHERE lane = $1 AND tenant_id = $2 AND state = 'queued'
AND available_at <= statement_timestamp()
ORDER BY available_at, id
LIMIT 1
), claimed AS (
UPDATE worker_job AS j
SET state = 'running', attempt = nextval('worker_attempt_seq')
FROM next_job, free_slot
WHERE j.id = next_job.id
RETURNING j.id, j.attempt
), occupied AS (
UPDATE tenant_slot AS s
SET job_id = claimed.id, attempt = claimed.attempt,
lease_until = statement_timestamp() + interval '60 seconds'
FROM claimed, free_slot
WHERE (s.lane, s.tenant_id, s.slot_no) =
(free_slot.lane, free_slot.tenant_id, free_slot.slot_no)
RETURNING claimed.id, claimed.attempt, s.slot_no, s.lease_until
)
UPDATE tenant_dispatch AS d
SET last_ticket = nextval('worker_dispatch_seq')
FROM occupied
WHERE d.lane = $1 AND d.tenant_id = $2
RETURNING occupied.*;
Run the work only after the transaction commits and a lease row was returned. A failed statement rolls back both job and slot changes. Renew a lease only when the attempt still matches and the lease has not expired by database time. Complete or reclaim under the tenant lock, comparing the same job ID and attempt before changing the job and slot. Reclaim abandoned work by moving it to a future available_at with backoff or to a terminal failure state when the attempt budget is exhausted.
A worker can become unreachable after calling a third-party API and before committing completion. A new attempt then runs with a different lease. Fencing blocks stale state changes within systems that check the attempt, but it cannot reverse a side effect that already crossed a network boundary. Send the provider a stable idempotency key per logical operation when supported. Otherwise, store evidence and use an explicit reconciliation policy for ambiguous responses. Use a database uniqueness constraint for local effects that can participate in the same transaction. Database-enforced invariants for financial side effects
Configure and observe the scheduling policy
# Illustrative policy for one deployment. Derive real values from service data.
lanes:
notifications:
pool_max_running: 8
tenant_max_running: 2
tenant_max_outstanding: 500
eligible_wait_p95_seconds: 5
bulk_imports:
pool_max_running: 16
tenant_max_running: 3
tenant_max_outstanding: 3000
eligible_wait_p95_seconds: 60
leases:
duration_seconds: 60
heartbeat_seconds: 15
max_attempts: 5
The pool cap is the aggregate across replicas. A process-local semaphore cannot enforce it across an autoscaled deployment. Use a controlled fleet envelope or a separate distributed capacity mechanism for global quotas. Record queue age for jobs eligible to run and separately report jobs waiting on tenant quota, retry delay, or downstream capacity. Kube autoscalers can consume custom and external metrics when a metrics adapter exposes them. Keep replicas bounded by database and vendor capacity. Kubernetes Horizontal Pod Autoscaling
Failure modes that reveal quota gaps
Prefetch becomes a second scheduling queue
A worker reserves a batch for one large tenant and starts only two jobs while other work stays invisible or unavailable. Compare broker in-flight counts, worker running counts, and time from reservation to execution. Reduce reservation windows for slow tasks and obtain a capacity slot as close to execution as possible. Pool separation helps when job durations are substantially different. Celery prefetch limits
A stale worker completes after a replacement started
Pause a worker beyond its lease, reclaim its job, then allow the original process to resume. Verify the old attempt cannot update job state or release the new attempt's slot. Test that a provider call uses the same idempotency key. Leases recover capacity and coordinate state. A suspended process can still consume physical resources after lease expiry, so add workload deadlines and process termination where the runtime supports them.
Retries occupy every tenant slot
Simulate a dependency outage, then restore it partway through a load test. Retrying immediately can repeatedly fill all slots for one tenant or overwhelm a recovering service. Release the slot between attempts, store a future eligibility time, apply jitter and a retry cap, and keep poison jobs out of the hot path. A visible terminal state lets support handle jobs requiring manual reconciliation.
Fairness metrics hide blocked work
During a mixed-tenant soak test, inspect both eligible wait and blocked wait. A healthy eligible-wait percentile can coexist with hours of quota-blocked bulk work. Track oldest ready age and unsuccessful attempts by workload class. Keep tenant details in controlled traces or dashboards with deliberate cardinality limits. Correlating worker logs with OpenTelemetry
Choose the right level of scheduling control
Broker fairness fits a high-throughput shared queue when the main goal is to protect quiet tenants' dwell times. Amazon SQS standard queues can apply fairness from MessageGroupId. This delivery feature neither enforces per-tenant rate caps nor provides FIFO ordering. Keep a separate execution quota when a tenant must stay below a strict limit. Amazon SQS fair queues
PostgreSQL-backed scheduling fits teams that need durable quota state and a database transaction around claims. Each dispatch touches hot rows and indexes. Benchmark claim contention, connection use, and vacuum impact as throughput grows. Redis can enforce low-latency admission counters where appropriate, but a split Redis/PostgreSQL claim introduces reconciliation if the services disagree about who owns a job.
Dedicated queues or worker cells fit customers with strict isolation or unusual workloads large enough to justify their own worker envelope. The cost is more routing, capacity planning, and operational overhead. Use a small number of classes or cells unless a durable customer-level requirement justifies additional isolation.
Estimate capacity and test quiet-tenant latency
In a hypothetical bulk pool of 16 workers, each chunk takes 12 seconds on average. A tenant capped at three active chunks can complete about 15 chunks per minute if it keeps its slots filled. A batch of 600 equal chunks would take roughly 40 minutes for that tenant before accounting for failures or overhead. The other 13 workers remain available for eligible work. These are simplified planning numbers. Confirm actual runtime, database pressure, and uneven chunk costs under load.
Publish a large batch from one tenant while several quiet tenants submit routine jobs. Compare p95 and p99 time-to-start for those quiet tenants against their baseline and service objective. Record worker utilization and drift in broker age. Scale only if the eligible backlog is broad enough to consume additional workers. A single capped tenant cannot use extra replicas without a corresponding policy change.
Frequently asked questions
How can I prevent a single tenant from consuming every worker?
Separate bulk work from latency-sensitive jobs, then enforce a per-tenant concurrency cap in each class. When a worker becomes available, choose among tenants with both ready work and a free slot. Add a separate admission policy to bound outstanding work so the backlog can still drain after a large burst.
Does a per-tenant rate limit replace worker quotas?
A rate limit controls how quickly work enters the system. A concurrency quota controls how much of it can run simultaneously. A few slow jobs can occupy a fleet while staying within a request-rate limit. Use both controls when tenants can submit workloads with substantially different runtime or resource needs.
What happens when a worker dies while it holds a tenant slot?
When the lease expires, a reclaimer compares the current attempt, releases capacity, and either requeues the job after backoff or records a terminal failure. The old worker must be fenced from changing the replacement attempt's state. External operations also need stable idempotency keys or a reconciliation process.
Which metric should drive autoscaling for a multi-tenant job queue?
Start with the age of eligible work in each workload class, then interpret it alongside service time, saturation, and downstream capacity. Track quota-blocked work separately. Extra replicas help when runnable demand is broadly distributed or a pool is genuinely saturated. They cannot resolve a single tenant's intentional execution cap.
Further reading
Diagnosing long waits in a shared worker pool? Talk to Dumb Potato about measuring the workload and designing tenant quotas.
