TL;DR
- Separate payment workers from API processes when their CPU, memory, provider quotas, retry patterns, or availability needs differ. Sharing a code image is fine; sharing the same scaling and process lifecycle is the coupling to remove.
- Size workers from measured arrival rate and service time, then verify queue age and recovery time under a provider slowdown. Worker count is not a static transaction-per-second promise.
- Budget database connections across every API replica and worker replica. A bigger worker pool can exhaust PostgreSQL even when CPU is idle.
- Make payment operations idempotent, persist state transitions, and handle shutdown without losing or duplicating external effects. A worker can repeat a request after an ambiguous timeout.
- Scale on eligible queue age, throughput, retries, and downstream saturation, with hard upper bounds on workers and provider concurrency.
Why payment work can overwhelm an API process
An API request that calls a payment provider, waits for a response, updates a ledger, and sends a notification ties up resources for the whole chain. The provider may be healthy but slower than normal. A pool of API workers can fill with requests that are waiting on network I/O, database connections can remain checked out, and unrelated endpoints can begin timing out. Retrying the same provider call from every request can make recovery harder by sending more work to a dependency that is already struggling.
A dedicated worker creates a separate process and scaling boundary for this work. The web tier accepts a command, validates authorization, writes durable intent, and returns an appropriate response. A worker claims a job, performs provider I/O, records the result, and retries or escalates according to policy. The request no longer waits for every downstream step.
Worker separation does not automatically make payments safe. The queue may redeliver a job. A provider can process a charge before a client connection times out. A deploy can stop a process between a remote success and a local state update. The design still needs stable idempotency keys, a durable state machine, reconciliation, and explicit ownership of ambiguous outcomes. See our payment idempotency guide and the webhook ingestion guide.
Separate deployment responsibilities without duplicating the application
Keep payment domain logic in a shared application package. Deploy distinct API and worker commands from the same versioned image when their dependencies and release lifecycle allow it. The API command serves HTTP. The worker command consumes named queues. This avoids maintaining a second implementation while letting each deployment use a different replica count, CPU and memory request, autoscaling policy, and connection budget.
Give processes only the credentials they need. API pods may need to create payment intents and write application state. Reconciliation workers may need provider read access and specific mutation capabilities. A webhook process may need only to verify signatures and write an inbox row. Prefer provider credentials scoped by environment and capability, and do not expose test and production credentials to the same workload.
Use separate queues or worker pools when task classes have different latency targets or resource profiles. A nightly reconciliation scan should not sit ahead of an interactive checkout confirmation. But too many tiny queues fragment capacity and make scheduling hard to understand. Start with a few classes such as latency-sensitive payment operations, webhook processing, and bulk reconciliation.
A container entrypoint should launch the worker as the main process so it receives shutdown signals. For example, use an exec-form command:
CMD ["celery", "-A", "app.celery_app", "worker", "-Q", "payments", "--loglevel=INFO"]
Build the application image once and override the command in the worker deployment. Keep config and secrets injected at runtime. This example shows process separation, not a complete production image or a universal queue recommendation.
Size capacity from arrivals, service time, and backlog goals
Begin with measured arrival rate by job class, not a single “payments per second” number. A payment authorization that normally takes 150 ms and occasionally waits several seconds has a different concurrency requirement than a local state update. Record service-time distributions, retry rates, provider concurrency limits, and the largest backlog the product can safely tolerate.
Little’s Law gives a useful first estimate: average in-flight work equals arrival rate multiplied by average time in the system. If a queue receives an illustrative 20 jobs per second and the average job occupies a worker for 0.4 seconds, the mean in-flight requirement is about 8 jobs. This is a starting estimate only. It ignores variance, retries, uneven work, outages, and the reserve capacity needed to drain a burst. Do not set a worker pool exactly to the mean and assume it will meet a tail-latency objective.
Define a drain objective. If a backlog contains B jobs, workers can complete at aggregate rate μ, and new work arrives at rate λ, then the backlog only shrinks when μ > λ. A rough drain time is B / (μ - λ). Estimate it separately for each queue class and rerun the calculation after applying provider rate limits and retry load.
CPU-bound jobs often need a process-oriented concurrency model. Network-bound jobs may support more in-flight I/O, but increasing concurrency can overload a provider or database. Measure CPU, memory, event-loop lag, provider latency, connection pool wait, and per-job service time. A high CPU limit with a saturated database pool does not justify adding worker replicas.
Budget PostgreSQL connections across the whole fleet
A worker process may own a connection pool, and each replica may start several processes. The maximum database connection demand is the sum of the API pools, worker pools, scheduled jobs, migrations, and administrative reserve. SQLAlchemy’s QueuePool, for example, can allow pool_size + max_overflow simultaneous connections per engine. Multiply that by the maximum number of replicas and engines before choosing worker concurrency. SQLAlchemy connection pool sizing
connection_budget =
api_max_replicas * api_pool_max
+ payment_worker_max_replicas * worker_pool_max
+ reconciliation_pool_max
+ operational_reserve
require connection_budget <= database_connection_budget
The example is arithmetic, not a target value. Include PgBouncer server-pool limits and PostgreSQL’s own capacity. Some drivers create pools lazily, but peak checkout capacity still matters. Set transaction and statement timeouts, keep transactions short, and never hold a database transaction open while waiting on a provider.
Persist a job claim or operation state, commit, then call the provider outside the transaction. Record the result in a new short transaction using a stable operation identifier and a compare-and-set state transition. This prevents a stalled network call from locking rows and consuming a database connection for its full duration.
Make payment work safe to retry
A queue usually offers at-least-once behavior or a retry path that can run the same logical job more than once. Celery’s late acknowledgement mode explicitly permits task re-execution after worker failure, so it recommends idempotent task functions. Celery task acknowledgement and idempotency
Use one idempotency key per logical payment operation, stable across retries. Store a request fingerprint so accidental reuse with different amount, currency, or customer data becomes a clear conflict. Persist provider object IDs and state transitions. A retry should ask whether the operation already exists before creating a new one. Do not generate a fresh provider key for every attempt.
Model ambiguous results directly. If a provider call times out after transmission, the local system may not know if it succeeded. Keep an outcome_unknown state, then query by provider idempotency key or stable merchant reference. Reconcile from canonical provider state before retrying an irreversible action. Use webhooks as asynchronous notifications that prompt a state refresh, not as an unquestioned ordered event log.
Separate payment authorization, capture, refund, and settlement into explicit operations with allowed transitions. A job should reject invalid transitions rather than infer them from a task name. For financial records, commit a balanced ledger transaction with the business state. A queue retry must not create a second ledger entry. See database-enforced ledger invariants.
Handle deployments and shutdowns deliberately
During a planned Kubernetes termination, the kubelet normally sends SIGTERM and allows a grace period before SIGKILL. The default grace period is 30 seconds, but payment jobs may need a different limit. Celery documents warm shutdown on TERM as allowing active tasks to finish, while a hard shutdown can interrupt work. Configure the worker’s shutdown behavior and Kubernetes grace period together. Kubernetes Pod termination · Celery worker shutdown stages
Keep task execution bounded by provider timeouts and application deadlines. If a task can run longer than the termination window, either checkpoint it or rely on a safe retry after interruption. Avoid acknowledging work before the system has enough durable state to recover it. Conversely, late acknowledgement means duplicate execution must be expected and made safe.
A rollout should stop assigning new work to a terminating worker, let in-flight work finish within its deadline, and leave unfinished work recoverable. Test an actual process kill at each boundary: before the request, after provider acceptance, before local commit, and after local commit but before acknowledgement. A payment provider’s idempotency contract determines which retries are safe and for how long.
Scale on queue behavior and protect the provider
Useful worker metrics include eligible queue age, oldest job age, arrival and completion rates, in-flight work, retries by error class, provider latency, provider throttles, and database pool wait. Queue depth alone can be misleading: a few long jobs can be more urgent than many quick ones. Alert on age relative to the service objective, and separate work waiting for a retry delay from work eligible to run.
Autoscale on a signal that changes before customer impact becomes severe, such as oldest eligible work age or queue wait time. Bound maximum replicas using the tightest provider, database, or CPU limit. Add a per-provider concurrency cap and use exponential backoff with jitter for retryable failures. A 429 or elevated provider latency should reduce pressure, not trigger unbounded scale-out.
Choose a retry budget and dead-letter policy. Permanent validation errors should not retry forever. Transient timeouts can retry after bounded backoff. A poison message should move to a review path with enough context for safe repair. Do not automatically replay a dead-lettered charge without checking provider state.
Frequently asked questions
Should payment workers use a separate container image from the API?
Not necessarily. A shared, immutable image with different commands often keeps code and dependency versions aligned while allowing separate deployments and resource limits. Build a separate image when the worker has materially different dependencies or security requirements, and keep shared domain behavior in a versioned package.
How many payment worker replicas should I run?
Estimate in-flight demand from measured arrival rate and service time, then validate queue age and drain time under burst and provider slowdown scenarios. Apply provider concurrency limits, database connection budgets, CPU and memory measurements, and a safe maximum replica count. There is no universal replica count or TPS conversion.
Can I acknowledge a payment task before calling the provider?
Only if durable state already guarantees another process can complete or reconcile the operation. Acknowledging before recording intent can lose work. Acknowledging after the provider call may cause the task to run again if the worker crashes before acknowledgement, so use stable idempotency keys and make the handler safe to repeat.
What should happen when a worker receives SIGTERM during a charge?
Stop accepting new tasks, allow the active attempt to finish within a configured deadline, and persist its outcome before exit. If the process is forcibly stopped or the provider response is ambiguous, leave the job recoverable and reconcile using the same idempotency key before issuing another mutation.
Separate the failure domains before scaling
A separately deployable worker protects the API from payment processing’s queueing, provider waits, retries, and resource profile. Its benefit depends on durable job state, idempotent operations, connection budgets, and graceful interruption. Start with explicit queue classes, measure service time and queue age, and cap the worker fleet at downstream capacity. If your payment workload is growing or difficult to reconcile, talk to our engineering team about worker isolation, provider limits, and payment recovery paths.
