Files
baserow/docs/decisions/018-celery-threads-and-task-time-limits.md
Davide Silvestri f5bc919473 feat(celery): make every task work on a threads worker, and use one in dev (#6926)
* chore(dev): run one threads Celery worker with beat in dev

The Docker and native dev stacks start a single Celery worker for every
queue, with redbeat embedded, instead of a worker, an export worker and a
beat process. It uses a new ThreadsPool that sends worker_process_init, so
telemetry and the lazy import check still run under the threads pool.

* fix(ws): stop closing every event loop's Redis pools after a broadcast

send_messages_to_channel_group called channel_layer.close_pools(), which
closes the pools of every event loop, including the ones other worker
threads are still sending with. Under the threads pool about a third of
broadcasts failed with "attached to a different loop" and some hung.
channels_redis now closes a loop's pools itself when that loop closes.

* fix(telemetry): keep Celery trace context per thread on threads workers

The Celery instrumentation keys a running task's span, context token and start
time by the task's id. A task replaced with self.replace(), like every
automation node, keeps its id, and on a threads worker the replacement can
start in another thread before the original ends. The original then ended the
replacement's span and detached its context from the wrong thread, logging
"Failed to detach context" and leaving its own context on the thread. That
state is now kept per thread.

* feat(celery): enforce soft and hard time limits in ThreadsPool

Celery's own threads pool ignores soft_time_limit and time_limit, so on a
threads worker tasks that rely on them would run on. ThreadsPool now raises
the limit in the task's thread, only while that task runs, so a limit never
reaches the next task of the thread. EMAIL_TIMEOUT stops a silent SMTP server
from blocking a worker thread forever.

* fix(chat-runs): cancel a run that keeps going after its deadline

The deadline only asks a run to stop. A run whose tools or provider call
ignore that request now gets 60 more seconds, is then cancelled, and is saved
as timed out. Celery's limit moves after that, so the run's own stop always
comes first. On a threads worker this is the only way to end it, because a
time limit can't reach a thread waiting inside async_to_sync.

* fix(premium): share one capped thread pool across AI field generations

Each generation started its own pool of
BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS threads, so a threads worker
running several jobs multiplied the threads and model calls. All generations
in a process now share one pool of that size. A prefork process runs one job
at a time, so nothing changes there.

* feat(celery): cancel queries at the hard limit and report overdue tasks

ThreadsPool checks every running task's time limits from one watchdog thread,
like the prefork pool's timeout handler, instead of starting timer threads
for each task. At the hard limit it also cancels the query the task's thread
is running, which the limit's exception can't interrupt.

A thread can't be killed, so a task still running 60 seconds after its hard
limit is reported to Sentry instead. Every limit reached is counted in
baserow.celery.task.time_limit, per task and limit.

* fix(airtable): time out requests to Airtable

Two Airtable import requests had no timeout, so a server that stopped
answering held the import, and on a threads worker its thread, forever. All
Airtable requests now use the same 3 minute read timeout.

* fix(celery): load sentry_sdk only when reporting an overdue task

The overdue report imported sentry_sdk at the top of baserow.config.celery,
which every process imports, so it was loaded even with Sentry off.

* chore: add a changelog entry for the Celery task timeouts

* fix(celery): raise threads pool time limits at the task's next query

An exception raised into a thread from outside can land right after a lock
is taken and before the code that releases it, leaving the lock held for
every thread of the worker. The pool now marks a reached limit and the
task's own next query raises it, once, through a connection execute
wrapper. The hard limit still cancels the running query, and raises
TimeLimitExceeded whatever the soft limit is. Limits end before Celery's
success callback runs. Savepoint queries are never interrupted, through
a helper shared with the periodic field update deadline.

* fix(celery): apply the worker default time limits on the threads pool

Celery passes CELERY_TASK_SOFT_TIME_LIMIT and CELERY_TASK_TIME_LIMIT to the pool and None per task when a task sets no limit. The prefork pool falls back to the pool's values; the threads pool now does too.

* fix(celery): keep threads pool time limits until running tasks end

The watchdog stopped before on_stop waited for the running tasks, so a task passing its limit during a warm shutdown was never stopped or reported.

* chore: name the emails the SMTP timeout covers in the changelog

EMAIL_TIMEOUT applies to the instance's own emails only. Automation and builder SMTP steps already time out after 30 seconds.

* chore(dev): drop dev.sh tabs for the removed Celery workers

The export and beat services are disabled, so attaching to them made the script exit before opening the remaining tabs.

* test(celery): cover thread time limits and savepoint rollback

* fix(ai): use one generation slot for nonpositive limits

* fix(chat): warn that an action may finish after a reply times out

* docs(celery): explain which timeout guarantees require prefork

* docs(celery): record the threads pool decision and task contract

* fix(chat): keep the worker slot until started tools finish

* fix(chat): warn visitors about repeating a timed-out request

* docs(chat): clarify when the stop grace period begins
2026-12-03 09:39:52 +01:00

3.5 KiB
Raw Permalink Blame History

ADR 018: Use Celery threads for I/O concurrency with cooperative time limits

Status Proposed
Date 2026-12-02
Issue https://github.com/baserow/baserow/issues/6931
Author Davide Silvestri (@silvestrid)

Summary

Run the development queues and beat in one threaded Celery worker. Offer threads as a production opt-in in the next rollout step. Prefork remains the production default and the appropriate choice when a task requires forced termination.

Context

With prefork, each concurrent task needs a child process with Django loaded. Keeping just one slot saves memory, but a long export or model call can occupy that worker while other tasks wait. On the laptop measured for this change, the prefork dev setup used 1.3–3.6 GB. The single threaded worker used 0.3–0.6 GB. Threads can share that memory and make progress while another task waits for I/O. Development measurements

Decision

Prefork can terminate and replace one child at the hard limit. Python has no safe equivalent for a running thread. Injecting an exception as a thread acquires a lock can leave the lock held. Restarting the process would interrupt every task in the worker.

On threads, Baserow delivers a pending time limit at the task thread's next ordinary Django query. At the hard limit it also asks PostgreSQL to cancel a query already running on that thread's connections. Code waiting elsewhere can continue past either limit. The worker reports a task still running 60 seconds after its hard limit and keeps serving work on its remaining slots.

Contract for task authors

  • Bound blocking calls where they happen. Give network and other blocking I/O finite timeouts. For multiple calls or retries, carry a deadline through the operation so each attempt uses the time remaining. A single Redis send can do useful work without ever reaching a SQL query.
  • Give long loops a place to stop. Check the deadline between bounded batches, before starting more work. Let time-limit exceptions unwind the current operation and release locks and connections. A broad exception handler that retries the same work can keep the worker slot occupied.
  • Account for work handed off. Cancelling a wait can leave a tool thread running or a remote request already accepted. A timeout alone does not make retrying a write safe. For example, a chat accepts another message after its grace period, and warns that an earlier tool may still finish a write. Background chat runs

Consequences

A cooperative task can stop at a safe boundary. If a library blocks indefinitely or ignores cancellation, the slot stays occupied until the task exits. Use the overdue metric and Sentry report to identify that task and fix the blocking operation. Workloads that need their local execution stopped independently belong on prefork. Neither pool can recall an external request or undo a committed write.

Threads also share CPU and the worker's process memory limit. A process crash loses all active tasks in that worker, and increasing concurrency can open more database connections. Before changing the production default, use the opt-in rollout to evaluate overdue tasks, worker memory, connection use and queue wait times. Rollout plan