Background Jobs & Workers
Relevant source files
The following files were used as context for generating this wiki page:
Polar utilizes a distributed background job system to handle asynchronous tasks that should not block the primary API request-response cycle. This system is critical for operations such as processing payments, syncing with GitHub, sending emails, and executing long-running business logic. The architecture relies on Dramatiq as the task processing library, with Redis serving as the primary message broker and job queue.
The background worker environment is decoupled from the FastAPI web server, allowing for independent scaling and failure isolation. Workers are responsible for consuming messages from Redis, executing the associated Python "actors," and managing database transactions automatically upon completion of a task.
Sources: AGENTS.md:16-20, DEVELOPMENT.md:8-25, CLAUDE.md:87-91
Architecture Overview
The background job system consists of three main components: the Task Producer (API), the Message Broker (Redis), and the Task Consumer (Worker).
- API (Producer): The FastAPI application triggers background jobs by enqueuing them. This is typically done within service layer methods after a database record is created or updated.
- Redis (Broker): Acts as the intermediary storage for queued tasks. It ensures that jobs are persisted until a worker is available to process them.
- Worker (Consumer): A dedicated process running Dramatiq that watches the Redis queues, picks up pending tasks, and executes the business logic defined in
tasks.pymodules.
High-Level Data Flow
The following diagram illustrates how a user request eventually triggers a background job.
The diagram shows the transition from a synchronous API request to an asynchronous background task.
Sources: DEVELOPMENT.md:12-25, server/CLAUDE.md:120-125
Core Components and Implementation
Actors and Tasks
In the Polar codebase, background jobs are referred to as "actors." These are defined using the @actor decorator. Actors are typically located in tasks.py files within their respective modules (e.g., polar/organization/tasks.py).
Each actor can be configured with specific properties such as priority. The system defines a TaskPriority enum to categorize job urgency.
| Priority | Usage |
|---|---|
HIGH | Time-sensitive tasks like payment processing. |
MEDIUM | Standard business logic and sync operations. |
LOW | Non-critical maintenance or cleanup tasks. |
Sources: server/CLAUDE.md:162-178, server/polar/worker.py
Session Management
One of the most critical aspects of the Polar worker architecture is automatic session management. Workers use an AsyncSessionMaker to create database sessions. Unlike the API layer, which manages sessions per request, the worker commits the database session automatically at the end of each successful task execution.
CRITICAL RULE: Developers must never call session.commit() manually within an actor. If a task fails (raises an exception), the transaction is not committed, preventing inconsistent database states.
Sources: AGENTS.md:129-135, server/CLAUDE.md:120-128, server/CLAUDE.md:168-178
Enqueueing Jobs
Jobs are added to the queue using the enqueue_job function. This function takes the actor name and any necessary arguments (typically UUIDs of the entities to be processed).
# Example from service layer
async def create(self, session: AsyncSession, create_schema: ResourceCreate) -> Resource:
resource = await repository.create(Resource(**create_schema.model_dump()))
# Enqueue background job - do NOT commit session here
enqueue_job("resource.created", resource_id=resource.id)
return resource
Sources: server/CLAUDE.md:120-128, server/CLAUDE.md:170-175
Operational Commands
Managing the background worker system during development involves specific uv run or dev commands.
Development Workflow
| Action | Command | Description |
|---|---|---|
| Start Worker | uv run task worker | Starts the Dramatiq worker process. |
| Start Worker (dev) | dev worker | Internal CLI command to start the worker. |
| Hot-Reloading | N/A | Worker uses --watch flag in Docker/dev setups to restart on code changes. |
Sources: AGENTS.md:36-40, DEVELOPMENT.md:46-51, DEVELOPMENT.md:183-186
Environment Setup
The worker requires access to the same environment variables as the API, specifically:
POLAR_REDIS_URL: For broker connectivity.POLAR_POSTGRES_URL: For database access.EMAIL_RENDERER_BINARY_PATH: For tasks involving email generation.
Sources: CLAUDE.md:31-36, CLAUDE.md:87-95
Error Handling and Retries
The background job system is designed to be resilient. When an actor encounters a PolarTaskError or other exceptions, the worker handles the failure state. Since session.commit() is only called on success, failures ensure that partial or corrupt data is not persisted to PostgreSQL.
In Docker-based environments, worker logs can be accessed specifically to debug task failures:
dev docker logs worker
Sources: AGENTS.md:129-135, DEVELOPMENT.md:164-165, server/CLAUDE.md:164-165
Summary
Background Jobs & Workers in Polar provide a robust mechanism for handling off-path latency and complex integrations. By leveraging Dramatiq and Redis, and enforcing strict session management patterns (automatic commits at task end), the system ensures high reliability and data integrity. Developers interact with this system primarily through the @actor decorator and the enqueue_job utility, adhering to the modular structure of the server/polar/ directory.