fix: two API processes by default and the worker drains its queue

The API ran as one uvicorn process, so a slow 150 MB PDF check at checkout
held every other request; WEB_CONCURRENCY now comes from API_WORKERS
(default 2, 1 restores one process) and the api /tmp grows to 512 MiB for
two checks at once. The worker delivered one outbox job per second; it now
drains up to 50 per pass before its periodic tasks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-09 16:24:07 -03:00
parent 63af984e83
commit 74ac2c978b
6 changed files with 60 additions and 4 deletions

View File

@@ -87,7 +87,7 @@ jobs:
# the generator's geometry. The provider suites use a fake transport: they
# prove the documented contract, not the integration.
- name: Print-file geometry and provider adapters
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats -v
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_worker_drain -v
- name: Runtime and retention regressions
run: |

View File

@@ -53,10 +53,13 @@ def cleanup():
c.execute("DELETE FROM dtf_local.security_events WHERE created_at<now()-interval '30 days'")
def tick():
"""Deliver at most one outbox job; True when there was one, False otherwise."""
global last_tick
processed = False
with connect() as c:
job = c.execute('SELECT * FROM dtf_local.outbox WHERE delivered_at IS NULL AND available_at <= now() ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1').fetchone()
if job:
processed = True
try:
receipt = adapters[job['provider']].deliver(job['event_key'], job['payload'])
c.execute('UPDATE dtf_local.outbox SET delivered_at=now(), receipt=%s, attempts=attempts+1, last_error=NULL WHERE id=%s', (Jsonb(receipt),job['id']))
@@ -64,6 +67,14 @@ def tick():
delay = min(1800, 2**min(job['attempts']+1, 10))
c.execute("UPDATE dtf_local.outbox SET attempts=attempts+1, last_error=%s, available_at=now() + %s * interval '1 second' WHERE id=%s", (str(exc),delay,job['id']))
last_tick = time.monotonic()
return processed
def drain(limit=50):
"""Deliver up to `limit` outbox jobs in one pass, so a backlog leaves at
once instead of one job per second (Critical Corrections item 9)."""
for _ in range(limit):
if not tick():
return
def tiny_keepalive():
"""Keep a connected Tiny authorised even while no orders are sent.
@@ -118,7 +129,7 @@ def loop():
global last_cleanup
while True:
try:
tick()
drain()
if time.monotonic()-last_cleanup > 60:
cleanup()
# Approved quotes unpaid for 24 h expire on their own (front 9).

View File

@@ -15,6 +15,8 @@ PUBLIC_HOST=dtf.example.invalid
KANBAN_HOST=kanban-dtf.example.invalid
SITE_PORT=8080
KANBAN_PORT=8081
# API processes: 2 by default; 1 runs one process, as before. API only.
API_WORKERS=2
R2_ENDPOINT=TBD
R2_PUBLIC_ENDPOINT=TBD

View File

@@ -213,13 +213,20 @@ services:
api:
image: ${API_IMAGE:-gitea.blyzer.com.br/blyzer/dtf-api}:${IMAGE_TAG:-latest}
environment: *app-environment
environment:
<<: *app-environment
# Two uvicorn processes by default (Critical Corrections item 2, step 1):
# a slow 150 MB PDF check no longer holds every request in the only one.
# API_WORKERS=1 restores one process without a new image.
WEB_CONCURRENCY: "${API_WORKERS:-2}"
networks: [backend, egress]
read_only: true
# Swarm ignores the short `tmpfs:` key: a read-only container then has no
# writable /tmp at all. The long volume syntax is what a stack honours.
# 512 MiB, not 256: with two processes each may write a 150 MB PDF from the
# grade check at the same time.
volumes:
- {type: tmpfs, target: /tmp, tmpfs: {size: 268435456}}
- {type: tmpfs, target: /tmp, tmpfs: {size: 536870912}}
healthcheck:
test: [CMD-SHELL, 'python -c "import os,urllib.request; r=urllib.request.Request(\"http://localhost:8000/health\",headers={\"Host\":os.environ[\"PUBLIC_HOST\"]}); urllib.request.urlopen(r,timeout=3)"']
interval: 15s

View File

@@ -223,6 +223,15 @@ If a service is refused, the contract uses other codes: set `CORREIOS_COD_PAC`
or `CORREIOS_COD_SEDEX`. Correios price by the box, so `JADLOG_CAIXA_CM` and the
package weights must be set (they already are for Jadlog).
## 9. API processes
`API_WORKERS` is how many uvicorn processes the API container runs (default 2;
`1` runs one process, as before). More than one keeps a slow checkout, such as
a PDF of up to 150 MB being checked, from holding every other request in the
only process; the API's `/tmp` is sized for two such checks at once. It applies
to the API only, never to the worker. Set it in the stack's environment and
redeploy.
## Current blocker
This is the final deployment shape, but it is not authorized for production

View File

@@ -0,0 +1,27 @@
"""The outbox worker drains a backlog instead of one job per second (item 9).
Run from the repository root: python3 -m unittest tests.test_worker_drain -v.
The worker imports psycopg and boto3, so a host without the API image's
dependencies cannot import it; CI runs this in the api container.
"""
import unittest
from unittest import mock
from app import worker
class WorkerDrainTest(unittest.TestCase):
def test_drain_stops_when_the_queue_is_empty(self):
with mock.patch.object(worker, 'tick',
side_effect=[True, True, True, False]) as tick:
worker.drain()
self.assertEqual(tick.call_count, 4)
def test_drain_stops_at_the_limit(self):
with mock.patch.object(worker, 'tick', return_value=True) as tick:
worker.drain()
self.assertEqual(tick.call_count, 50)
if __name__ == '__main__':
unittest.main()