Multi-Worker Mode
Protean can run multiple Engine worker processes from a single CLI invocation
using the --workers flag. The Supervisor spawns N independent processes,
each running its own Engine with a dedicated event loop and domain
initialization. Workers coordinate implicitly through Redis consumer groups and
database-level locking. They need no IPC or shared memory.
When to Use Multiple Workers
| Scenario | Recommendation |
|---|---|
| Low-volume domains, development | Single worker (--workers 1, the default) |
| High message throughput | Multiple workers to parallelize processing |
| CPU-bound handlers | Multiple workers to utilize multiple cores |
| High availability | Multiple workers so surviving workers continue if one crashes |
Multiple workers are most effective with StreamSubscription, where Redis consumer groups distribute messages across consumers automatically. Each message is processed by exactly one worker.
Prerequisite: Stream subscriptions
Multi-worker mode requires default_subscription_type = "stream" in your
domain configuration. This enables the
transactional outbox and
Redis Stream-based consumer groups that distribute messages across workers.
# domain.toml
[server]
default_subscription_type = "stream"
See Subscription Types for details on the two subscription types and Configuration Reference for the full list of server options.
Note
EventStoreSubscription does not distribute messages across workers. Multiple workers will each process the same messages independently, which is safe for idempotent projections but wasteful for side-effecting handlers.
Starting Multiple Workers
# Start 4 worker processes
protean server --domain=my_domain --workers 4
# With debug logging
protean --log-level DEBUG server --domain=my_domain --workers 4
# With test mode (each worker processes available messages and exits)
protean server --domain=my_domain --workers 4 --test-mode
How It Works
The multi-worker architecture follows the prefork model:
-
The Supervisor spawns N worker processes using Python's
multiprocessingmodule with thespawnstart method (safe on all platforms, avoids fork-related issues with asyncio event loops and database connections). -
Each worker independently derives the domain from the domain path, initializes it, creates its own Engine, and runs the event loop.
-
Workers coordinate through infrastructure:
- Redis consumer groups distribute stream messages so each message is processed by exactly one worker.
-
Database-level locking in the OutboxProcessor prevents duplicate publishing when multiple workers poll the outbox table.
-
The Supervisor monitors workers and handles shutdown signals.
Worker Coordination
Stream Messages
Redis consumer groups distribute messages across workers automatically. When multiple workers subscribe to the same stream, Redis assigns each message to one consumer. No application-level coordination is needed.
Outbox Processing
Each worker runs its own OutboxProcessor. To prevent multiple workers from
publishing the same outbox message, the processor uses database-level row
locking. A worker claims a message by transitioning it from PENDING to
PROCESSING with an atomic operation. If another worker tries to claim the
same message, the operation fails and that worker moves on.
See Outbox Pattern for details on the locking mechanism.
Signal Handling
The Supervisor installs handlers for SIGINT, SIGTERM, and SIGHUP (where
available). When a signal is received:
- The Supervisor sends
SIGTERMto each living worker process. - Workers receive the signal and begin their own graceful shutdown (completing current message processing, persisting subscription positions).
- The Supervisor waits for workers to exit. The wait is the workers'
server.drain_timeoutplus 5 seconds, and never less than 30 seconds. - Workers that do not stop within the timeout are forcefully killed with
SIGKILL.
A worker can stop after it reads a message and before it handles the message.
Redis keeps that message pending. When a worker starts, it claims the pending
messages last delivered at least server.reclaim_idle_seconds
earlier, and handles them. A partitioned subscription (sequential_by) does
not wait for this threshold: the partition's next owner claims its pending
messages through the lease handover.
The Supervisor ignores a second signal that arrives while shutdown is already in progress.
SIGTERM to the Supervisor is the only way to quiesce every worker at once.
POST /drainz drains the single worker whose health server answered it, since
workers share no IPC. See
/drainz drains one worker.
Monitoring Workers
The Supervisor continuously monitors worker processes:
- Clean exit (exit code 0): The worker is removed from the pool and logged.
- Crash (non-zero exit code): The worker is removed, the event is logged as an error, and the Supervisor's exit code is set to 1.
- All workers exited: The Supervisor exits with the appropriate code.
Note
The Supervisor does not automatically restart crashed workers. If you need
automatic restarts, use a process manager (systemd, Docker, Kubernetes) to
restart the entire protean server command.
Exit Codes
| Code | Meaning |
|---|---|
| 0 | All workers exited cleanly |
| 1 | One or more workers crashed |
| Non-zero (from CLI) | Propagated from the Supervisor to the CLI |
Programmatic Usage
You can use the Supervisor directly in Python code:
from protean.server.supervisor import Supervisor
supervisor = Supervisor(
domain_path="my_package.domain",
num_workers=4,
test_mode=False,
log_level="INFO",
)
run() spawns the workers and blocks until they all exit:
# fragment
supervisor.run()
print(f"Exit code: {supervisor.exit_code}")
log_level, log_format and log_config set up logging in each worker the way
the CLI's --log-level, --log-format and --log-config flags do. log_config
takes a dictConfig dict. log_level must be one of DEBUG, INFO,
WARNING, ERROR or CRITICAL, and log_format one of auto, console or
json. Any other value raises ValueError.
The log_level, log_format, and log_config arguments do not set up logging
in your own process. With more than one worker, every worker sends its records
to the supervisor, and the supervisor writes them with the handlers on its root
logger. Their levels and formatters decide what you see. With no handlers
there, the supervisor writes to stdout at
INFO, so worker DEBUG records are dropped. Set up logging before you call
run():
from protean.utils.logging import configure_logging
configure_logging(level="DEBUG")
supervisor = Supervisor("my_package.domain", num_workers=4, log_level="DEBUG")
Then call supervisor.run().
The debug argument is deprecated and is removed in 0.20.0. Pass
log_level="DEBUG" instead. Reloader takes the same arguments and has the
same deprecation.
Production Deployment
systemd
[Unit]
Description=Protean Message Server (4 workers)
After=network.target redis.target
[Service]
Type=simple
User=app
WorkingDirectory=/app
Environment=PROTEAN_ENV=production
ExecStart=/app/.venv/bin/protean server --domain=my_domain --workers 4
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
Docker
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
WORKDIR /app
COPY . .
RUN uv sync
ENV PROTEAN_ENV=production
CMD ["uv", "run", "protean", "server", "--domain=my_domain", "--workers", "4"]
Kubernetes
With multiple workers per pod, you can reduce replica count while maintaining throughput. Each pod runs a Supervisor with N workers:
apiVersion: apps/v1
kind: Deployment
metadata:
name: protean-server
spec:
replicas: 2 # 2 pods × 4 workers = 8 total workers
selector:
matchLabels:
app: protean-server
template:
spec:
containers:
- name: server
image: my-app:latest
command: ["protean", "server", "--domain=my_domain", "--workers", "4"]
resources:
requests:
cpu: "1000m"
memory: "512Mi"
Related pages
- Running the Server: CLI options, single-worker mode, and general deployment guidance
- Outbox Pattern: How the outbox ensures reliable delivery in multi-worker deployments
- Engine Architecture: How each worker's Engine processes messages