High-Load Infrastructure¶
FlowController (backpressure)¶
FlowController
¶
Publish-side flow control.
Usage::
fc = FlowController(BackpressureConfig(max_in_flight=500, rate_limit=1000))
# Before publish:
if fc.acquire(timeout=5.0):
transport.publish(envelope)
fc.release()
else:
# message dropped or error raised (depends on on_blocked)
...
# Register with transport callbacks:
transport.on_blocked(fc.on_blocked)
transport.on_unblocked(fc.on_unblocked)
Source code in src/rabbitkit/highload/backpressure.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 | |
Attributes¶
is_blocked: bool
property
¶
True if connection is currently blocked by RabbitMQ.
in_flight: int
property
¶
Current number of in-flight (unconfirmed) publishes.
Methods:¶
on_blocked() -> None
¶
Called when RabbitMQ signals connection.blocked.
Source code in src/rabbitkit/highload/backpressure.py
on_unblocked() -> None
¶
Called when RabbitMQ signals connection.unblocked.
Source code in src/rabbitkit/highload/backpressure.py
acquire(timeout: float | None = None) -> bool
¶
Acquire a publish slot.
Checks (in order): not blocked, in-flight < max, rate OK.
Returns True if slot acquired, False if dropped.
Raises BackpressureError if on_blocked == "raise" and blocked.
With on_blocked="wait" a race loss (the slot we waited for was
taken by another contender) re-loops instead of silently dropping —
mirroring the async path (I-9). The loop is bounded by the deadline
derived from timeout / blocked_timeout.
Source code in src/rabbitkit/highload/backpressure.py
release() -> None
¶
acquire_async(timeout: float | None = None) -> bool
async
¶
Async variant of acquire.
Source code in src/rabbitkit/highload/backpressure.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | |
release_async() -> None
async
¶
Async variant of release.
Source code in src/rabbitkit/highload/backpressure.py
BatchPublisher¶
BatchPublisher
¶
Buffer outgoing envelopes and flush as a batch.
When flush_interval_ms > 0 (default 50 ms), a background timer
fires periodically to flush any buffered envelopes even if
batch_size has not been reached. The timer starts lazily on the
first call to add() and is cancelled by close() / close_async().
max_in_flight is reserved for future async-confirm support and has
no runtime effect in the current synchronous-confirm model.
NOTE (throughput): this is a buffering/timing helper, not wire-level
batching. flush publishes each buffered envelope via publish_fn, so
if publish_fn awaits a confirm per message the confirms do not pipeline —
you get ergonomics, not extra throughput. For high-volume confirmed
publishing, pipeline confirms yourself (publish many, then await) or use the
transactional outbox; for safety-critical events, always use the outbox.
Usage::
bp = BatchPublisher(
config=BatchPublishConfig(batch_size=50, flush_interval_ms=100),
publish_fn=transport.publish,
confirm_fn=transport.wait_for_confirms, # optional
)
bp.add(envelope1)
bp.add(envelope2)
...
bp.flush() # publishes all buffered
bp.close() # flush remaining + cancel timer
Source code in src/rabbitkit/highload/batch.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
Attributes¶
pending: int
property
¶
Number of envelopes buffered but not yet flushed.
Methods:¶
add(envelope: MessageEnvelope) -> None
¶
Add an envelope to the batch buffer.
Auto-flushes when batch_size is reached. Starts the interval
timer on the first call when flush_interval_ms > 0.
Source code in src/rabbitkit/highload/batch.py
flush() -> int
¶
Publish all buffered envelopes.
Returns the number of envelopes published.
Source code in src/rabbitkit/highload/batch.py
close() -> int
¶
Flush remaining envelopes, cancel the interval timer, and clean up.
Returns the number of envelopes flushed.
Source code in src/rabbitkit/highload/batch.py
add_async(envelope: MessageEnvelope) -> None
async
¶
Async: add envelope; auto-flush at batch_size.
Starts the async interval loop on the first call when
flush_interval_ms > 0.
Source code in src/rabbitkit/highload/batch.py
flush_async() -> int
async
¶
Async: publish all buffered envelopes.
Source code in src/rabbitkit/highload/batch.py
close_async() -> int
async
¶
Async: cancel the interval loop, flush remaining, and clean up.
Source code in src/rabbitkit/highload/batch.py
BatchAcker¶
BatchAcker
¶
Accumulate delivery tags and ack in batches.
Uses multiple=True on the maximum delivery tag in the batch.
When flush_interval_ms > 0 (default 200 ms), a background timer
fires periodically to ack any buffered tags even if batch_size has
not been reached. The timer starts lazily on the first call to
add() and is cancelled by close() / close_async().
Ownership rules:
- Channel-scoped — NEVER cross channels
- Handlers MUST NOT call msg.ack() when BatchAcker is active
- Compatible with AUTO and NACK_ON_ERROR policies only
Usage (sync / pika) — ack_fn MUST NOT be a raw channel.basic_ack.
The interval timer fires flush() from a background
threading.Timer thread, not pika's connection I/O thread; pika
channel methods are not thread-safe, so a direct channel.basic_ack
reference here is a real cross-thread violation waiting to happen the
first time the timer (rather than add()) triggers the flush.
Marshal onto the I/O thread instead, e.g. via
connection.add_callback_threadsafe::
def safe_ack(delivery_tag: int, multiple: bool = False) -> None:
connection.add_callback_threadsafe(
lambda: channel.basic_ack(delivery_tag=delivery_tag, multiple=multiple)
)
ba = BatchAcker(
config=BatchAckConfig(batch_size=50, flush_interval_ms=200),
ack_fn=safe_ack,
)
ba.add(delivery_tag=1)
ba.add(delivery_tag=2)
...
ba.flush() # ack(max_tag, multiple=True)
ba.close() # flush remaining + cancel timer
The async path (add_async/flush_async) has no such hazard —
_interval_loop_async schedules via asyncio.create_task on the
same event loop the aio-pika channel already runs on, so an aio-pika
channel.basic_ack (a coroutine function) can be passed directly as
ack_fn.
Source code in src/rabbitkit/highload/batch.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
Attributes¶
pending: int
property
¶
Number of delivery tags buffered.
Methods:¶
add(delivery_tag: int) -> None
¶
Add a delivery tag to the batch.
Auto-flushes when batch_size is reached. Starts the interval
timer on the first call when flush_interval_ms > 0.
Source code in src/rabbitkit/highload/batch.py
flush() -> int
¶
Ack all buffered tags using the max tag with multiple=True.
Returns the number of tags acked.
Source code in src/rabbitkit/highload/batch.py
close() -> int
¶
Flush remaining tags, cancel the interval timer, and clean up.
Source code in src/rabbitkit/highload/batch.py
add_async(delivery_tag: int) -> None
async
¶
Async: add tag; auto-flush at batch_size.
Starts the async interval loop on the first call when
flush_interval_ms > 0.
Source code in src/rabbitkit/highload/batch.py
flush_async() -> int
async
¶
Async: ack all buffered tags.
Source code in src/rabbitkit/highload/batch.py
close_async() -> int
async
¶
Async: cancel the interval loop, flush remaining, and clean up.
Source code in src/rabbitkit/highload/batch.py
Worker Pools¶
SyncWorkerPool
¶
Thread pool for concurrent sync message processing.
Wraps a handler callback to execute it in a thread pool with limited concurrency.
Usage::
pool = SyncWorkerPool(config=WorkerConfig(worker_count=4))
pool.start()
# Use pool.submit(callback, message) instead of callback(message)
pool.stop()
Source code in src/rabbitkit/concurrency.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
Attributes¶
worker_count: int
property
¶
Return the configured worker count.
pending_count: int
property
¶
Number of tasks currently pending/running.
Methods:¶
start() -> None
¶
Start the worker pool.
Uses daemon worker threads (see :class:_DaemonWorkerPool) so a stuck
handler cannot keep the process alive past stop() — important for
k8s graceful shutdown where terminationGracePeriodSeconds must be
honored without relying on SIGKILL.
Source code in src/rabbitkit/concurrency.py
stop(timeout: float | None = None, pump: Callable[[], None] | None = None) -> None
¶
Stop the worker pool, waiting for in-flight tasks.
Cancels pending (not-yet-started) futures and bounds the wait for
running ones by timeout (default WorkerConfig.stop_timeout).
Because workers are daemon threads, any task that does not finish in
time is abandoned and the process can still exit cleanly — SIGKILL is
no longer required as a backstop.
H2: when pump is given (SyncBroker.stop() passes
SyncTransport.pump), the wait is polled in short slices with
pump called between them, instead of one blocking
concurrent.futures.wait(timeout=effective). A worker thread
finishing its handler acks/nacks by marshaling onto the transport's
owner thread via _run_on_io_thread — without something draining
the connection's I/O loop while this method blocks, those marshaled
callbacks would never run (they'd eventually time out on the worker
side, or — before this fix — the transport fell back to an unsafe
inline cross-thread call). pump must be safe to call from whichever
thread calls stop() (i.e. stop() must run on the transport's
owner thread when pump is given). Without pump, behavior is
unchanged: a single blocking wait for the full effective timeout.
Source code in src/rabbitkit/concurrency.py
submit(callback: Callable[[RabbitMessage], None], message: RabbitMessage) -> None
¶
Submit a message for processing.
If worker_count=1 (default), runs synchronously in the current thread. Otherwise, submits to the thread pool.
Source code in src/rabbitkit/concurrency.py
AsyncWorkerPool
¶
Semaphore-based concurrent async message processing.
Limits the number of concurrently processing async handlers.
Usage::
pool = AsyncWorkerPool(config=WorkerConfig(worker_count=4))
pool.start()
await pool.submit(callback, message)
await pool.stop()
Source code in src/rabbitkit/concurrency.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 | |
Attributes¶
worker_count: int
property
¶
Return the configured worker count.
pending_count: int
property
¶
Number of tasks currently pending/running.
Methods:¶
start() -> None
¶
Start the worker pool.
Source code in src/rabbitkit/concurrency.py
stop(timeout: float | None = None) -> None
async
¶
Stop the worker pool, waiting for in-flight tasks.
R-TaskGroup: rather than asyncio.wait + a manual task.cancel()
loop, we gather(*tasks, return_exceptions=True) bounded by
asyncio.timeout (the 3.11+ idiom). Tasks that don't finish before
the deadline are cancelled and awaited once more so their
CancelledError is consumed rather than leaking as "Task was
destroyed but it is pending" warnings.
H12: a task cancelled by the deadline is not guaranteed to have
reached its own ack/nack — CancelledError is a
BaseException, so it skips right past the pipeline's
except Exception handling and the message is left unsettled.
Rather than leave that to the implicit requeue-on-unacked-channel-close
behavior when the transport eventually disconnects, any message still
unsettled after a task is abandoned is nacked (requeue) here and
logged by delivery tag — an explicit, immediate, observable
redelivery instead of an implicit one.
Source code in src/rabbitkit/concurrency.py
submit(callback: Callable[[RabbitMessage], Awaitable[None]], message: RabbitMessage) -> None
async
¶
Submit a message for concurrent processing.
If worker_count=1, runs directly (no semaphore). Otherwise, acquires semaphore slot before executing.
H12: refuses (nacks for redelivery) instead of scheduling an unawaited
task when the pool isn't running — e.g. a delivery callback firing
after stop() already cleared _tasks. Nothing would ever await
that task, so it would silently race the event loop's own shutdown
instead of the message being cleanly settled.
Source code in src/rabbitkit/concurrency.py
WorkerConfig
dataclass
¶
Consumer concurrency configuration.
Accepted by broker.start(), NOT part of RabbitConfig. Added in 0.2.0.
stop_timeout (H12): a FALLBACK drain deadline for the worker pool's
stop() — consulted only when no explicit timeout is passed. On the
standard shutdown path (broker.stop()) the pool drain budget is
ConsumerConfig.graceful_timeout, NOT this field — tune THAT (and
keep terminationGracePeriodSeconds a few seconds above it) for
Kubernetes; setting only stop_timeout there has no effect
(architect review M2 — the old text here said the opposite).
stop_timeout matters when you drive a worker pool directly. A
handler still running past this deadline is abandoned, not killed:
the sync pool's daemon thread keeps running in the background (it is
never forcibly stopped — Python cannot interrupt an arbitrary thread),
and the async pool cancels the task (which does not guarantee the
handler reaches its own ack/nack — CancelledError is a
BaseException and is not caught by the pipeline's exception
handling). Either way the abandoned delivery is logged by delivery
tag/message id, and — for the async pool — nacked for redelivery
immediately rather than relying on the implicit requeue that happens
when the connection eventually closes. Because the original handler may
still complete its side effects after abandonment, handlers must be
idempotent under at-least-once delivery regardless of stop_timeout.
Source code in src/rabbitkit/core/config.py
SyncBatchPublisher¶
Pipelined publisher confirms for sync code on a dedicated
SelectConnection I/O thread — raises the ~0.9k msg/s blocking-confirm
ceiling for callers who adopt it. Standalone by design (not wired into
SyncBroker.publish).
SyncBatchPublisher
¶
Pipelined-confirm publisher on a dedicated pika.SelectConnection.
Thread-safe: any number of caller threads may publish() concurrently.
Each call blocks only for ITS OWN confirm (bounded by confirm_timeout),
while the I/O thread keeps the channel's confirm window full — confirms
for many in-flight messages are serviced concurrently instead of one
blocking round-trip per message.
Standalone-only (see module docstring): not wired into SyncBroker.
Source code in src/rabbitkit/sync/batch.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 | |
Methods:¶
start(ready_timeout: float = 30.0) -> None
¶
Spawn the I/O thread and block until the confirm channel is ready.
Raises TimeoutError after ready_timeout if the broker never
becomes reachable, or RuntimeError if the I/O thread gave up
(connect attempts exhausted). Idempotent while running.
Source code in src/rabbitkit/sync/batch.py
close(timeout: float = 10.0) -> None
¶
Stop accepting publishes, drain briefly, fail stragglers, shut down.
Waits (bounded by timeout) for in-flight confirms to settle, then
fails any stragglers with PublishStatus.ERROR (M17: never silent),
stops the ioloop and joins the I/O thread. Idempotent.
Source code in src/rabbitkit/sync/batch.py
publish(envelope: MessageEnvelope, timeout: float | None = None) -> PublishOutcome
¶
Publish envelope and block until ITS confirm settles.
Returns CONFIRMED / NACKED / RETURNED per the broker's verdict,
TIMEOUT if no verdict arrived within timeout (default
confirm_timeout), or ERROR if the publisher is closed,
disconnected, or the connection died with this message in flight.
Never raises for transport-level failures; never hangs.