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.
Flush semantics (plan §4.2):
flush()returns the number of envelopes whose publish did not fail locally (CONFIRMED + UNKNOWN) — the legacy int contract — and stores the full :class:FlushReporton :attr:last_flush. Use :meth:flush_reportto get the report directly.- A
publish_fnthat RAISES mid-batch stops the flush; the items already published keep their real outcomes, the raising item isUNKNOWN(it may have reached the broker), and the unsent tail is preserved onreport.unsent— thenBatchFlushErroris raised. Nothing is silently put back into the buffer. - A
publish_fnthat returns a non-okPublishOutcome(NACKED, RETURNED, TIMEOUT...) is recorded per item — success is never inferred from loop iterations. - Background-timer failures are exposed via :attr:
last_errorand the optionalon_errorcallback instead of dying silently on the timer thread.
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 use broker.publish_many (bounded, per-item outcomes) or the
pipelined AsyncBatchPublisher / SyncBatchPublisher.
Source code in src/rabbitkit/highload/batch.py
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 | |
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. Raises
:class:BatchClosedError after close().
Source code in src/rabbitkit/highload/batch.py
flush_report() -> FlushReport
¶
Publish all buffered envelopes and return the full :class:FlushReport.
Raises :class:BatchFlushError (carrying the report) if a publish or
the confirm step raised.
Source code in src/rabbitkit/highload/batch.py
flush() -> int
¶
Publish all buffered envelopes.
Returns the number of envelopes whose publish did not fail locally.
See :meth:flush_report for per-item detail (also on :attr:last_flush).
Source code in src/rabbitkit/highload/batch.py
close() -> int
¶
Flush remaining envelopes, cancel the interval timer, and clean up.
Idempotent. Returns the number of envelopes flushed on THIS call.
Source code in src/rabbitkit/highload/batch.py
add_async(envelope: MessageEnvelope) -> None
async
¶
Async: add envelope; auto-flush at batch_size. Raises
:class:BatchClosedError after close_async().
Source code in src/rabbitkit/highload/batch.py
flush_report_async() -> FlushReport
async
¶
Async: publish all buffered envelopes and return the :class:FlushReport.
Source code in src/rabbitkit/highload/batch.py
flush_async() -> int
async
¶
close_async() -> int
async
¶
Async: cancel the interval loop, flush remaining, and clean up. Idempotent.
Source code in src/rabbitkit/highload/batch.py
BatchAcker¶
Default mode is individual (one multiple=False frame per tag). The legacy
cumulative ack(max_tag, multiple=True) is opt-in via
BatchAckConfig(mode="cumulative", ordered_exclusive_owner=True). For safe
coalescing under arbitrary completion order see
CoalescingAcker.
BatchAcker
¶
Accumulate delivery tags and ack them in batches.
Default mode "individual" (safe): flush() issues one
ack_fn(tag, multiple=False) per buffered tag. Submitting completed
tags 1 and 3 acks exactly 1 and 3 — tag 2, still processing on the same
channel, is untouched. This is a bulk API even though it emits one frame
per tag; correctness comes before wire savings.
Mode "cumulative" (opt-in, legacy): ack_fn(max_tag,
multiple=True). RabbitMQ settles every outstanding tag <= max_tag
on the channel, so this is only safe when this acker is the channel's
sole settler and completions arrive in tag order. BatchAckConfig
refuses the mode without ordered_exclusive_owner=True. For safe
coalescing under arbitrary completion order use :class:CoalescingAcker.
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. Marshal onto the I/O thread, 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), ack_fn=safe_ack)
ba.add(delivery_tag=1)
ba.add(delivery_tag=3)
ba.flush() # ack(1, multiple=False); ack(3, multiple=False)
ba.close() # flush remaining + cancel timer
The async path (add_async/flush_async) schedules on the same event
loop the aio-pika channel runs on, so an aio-pika channel.basic_ack
coroutine function can be passed directly as ack_fn.
Source code in src/rabbitkit/highload/batch.py
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 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 | |
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. A tag already
buffered is ignored (a double completion must not double-ack).
Raises :class:BatchClosedError after close().
Source code in src/rabbitkit/highload/batch.py
flush() -> int
¶
Ack all buffered tags. Returns the number of tags acked.
close() -> int
¶
Flush remaining tags, cancel the interval timer, and clean up. Idempotent.
Source code in src/rabbitkit/highload/batch.py
add_async(delivery_tag: int) -> None
async
¶
Async: add tag; auto-flush at batch_size.
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. Idempotent.
Source code in src/rabbitkit/highload/batch.py
Flush accounting¶
FlushReport
dataclass
¶
Complete per-item accounting for one flush.
unsent is the tail that was never handed to publish_fn because an
earlier publish raised. It is NOT re-buffered automatically (safety
invariant 7 — no blind replay of a partially successful batch); the
caller decides.
Source code in src/rabbitkit/highload/batch.py
FlushItem
dataclass
¶
Disposition of one envelope in a flush.
Source code in src/rabbitkit/highload/batch.py
BatchFlushError
¶
Bases: RuntimeError
A flush did not complete cleanly. report has the full accounting
(including the unsent tail). Raised by flush() only when a publish
call RAISED or the confirm step raised — a non-ok PublishOutcome
returned by publish_fn is recorded in the report, not raised.
Source code in src/rabbitkit/highload/batch.py
BatchClosedError
¶
Per-channel ack isolation¶
One acker per channel — delivery tags are a per-channel counter. See Bulk Operations for the contract.
CoalescingAckerGroup
¶
One :class:CoalescingAcker per channel, created on demand.
rabbitkit gives every subscriber queue its own channel, and delivery tags are a PER-CHANNEL counter — so a consumer with several queues needs several ledgers::
Channel A → CoalescingAcker A → SettlementCoordinator A
Channel B → CoalescingAcker B → SettlementCoordinator B
This group keeps that isolation for you: factory(channel) builds a
fully wired acker (its ack_fn/nack_fn/reject_fn bound to THAT
channel — only you know how to reach your transport), the group caches it
per channel, and every per-delivery call carries the channel so a
cross-channel mistake raises :class:ChannelMismatchError instead of
acking the wrong messages.
Channels are used as dict keys (all pika/aio-pika channel objects are
identity-hashable). The group holds a strong reference to each channel it
settles on, so call :meth:on_reconnect when one is rebuilt (or
:meth:reset when the whole connection is) to drop it.
Correctness does NOT depend on you making that call: a rebuilt channel is
a different object, so the next :meth:for_channel builds a fresh acker
with an empty ledger and the stale one is never consulted again. Calling
it releases the retired acker (and its channel reference) promptly and
keeps the metrics honest.
Wiring :meth:reset to the transport's on_reconnect hook is safe.
The hook fires once per rebuilt connection (publisher and consumer, on
both brokers, also for a broker-closed connection), after aio-pika has
restored the consumers, so restored channels may already be delivering
when it runs. :meth:reset therefore drops only the ledgers of channels
that are closed and leaves live ones alone. Dropping a live ledger would
leave its deliveries unacked on a channel the broker still considers
healthy, so they would never be redelivered.
Usage::
def build(channel: Any) -> CoalescingAcker:
return CoalescingAcker(
ack_fn=lambda t, m: loop.create_task(channel.basic_ack(t, multiple=m)),
nack_fn=lambda t, r: loop.create_task(channel.basic_nack(t, requeue=r)),
reject_fn=lambda t, r: loop.create_task(channel.basic_reject(t, requeue=r)),
config=BatchAckConfig(batch_size=50, flush_interval_ms=200),
channel_key=channel,
marshal=loop.call_soon_threadsafe, # required with an interval timer
)
group = CoalescingAckerGroup(factory=build)
@broker.subscriber(queue="orders", ack_policy=AckPolicy.MANUAL)
async def handle(body: bytes, msg: RabbitMessage) -> None:
channel = msg.raw_message.channel
group.register(channel, msg.delivery_tag)
...
group.complete(channel, msg.delivery_tag)
Source code in src/rabbitkit/highload/batch.py
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 | |
Attributes¶
channels: int
property
¶
Number of channels with a live acker.
pending: int
property
¶
Registered-but-unsettled deliveries across every channel.
metrics: dict[str, float]
property
¶
Per-channel metrics summed across the group (coalescing_ratio
is recomputed from the totals, not averaged).
Methods:¶
for_channel(channel: Any) -> CoalescingAcker
¶
Return (creating on first use) the acker that owns channel.
Source code in src/rabbitkit/highload/batch.py
register(channel: Any, delivery_tag: int) -> None
¶
Register a delivery BEFORE its handler runs, on channel's ledger.
abandon(channel: Any, delivery_tag: int) -> None
¶
cancel(channel: Any, delivery_tag: int) -> None
¶
flush(reason: FlushReason = FlushReason.MANUAL) -> GroupFlushReport
¶
Flush every channel's acker; never let one channel's failure skip the others (each acker records its own errors in its report).
Source code in src/rabbitkit/highload/batch.py
on_reconnect(channel: Any) -> tuple[int, ...]
¶
One channel was rebuilt: drop its ledger and retire its acker.
Returns the dropped delivery tags (the broker redelivers them). The
replacement channel is a different object, so the next
:meth:for_channel builds a fresh acker for it. Unknown channels are
a no-op, so this is safe to call from a reconnect hook that does not
track which channels were in use.
Source code in src/rabbitkit/highload/batch.py
reset() -> int
¶
The connection was rebuilt: drop the ledger of every channel that is CLOSED. Returns the total number of dropped tags.
A channel that is still open keeps its ledger. The reconnect hook
fires after aio-pika has already restored the consumers, and once
per connection (publisher and consumer), so by the time it runs a
restored channel may already be delivering. Dropping that live
ledger stranded its deliveries: their complete() found no
ledger, nothing was ever acked, and the broker never redelivered
them because the channel stayed open. A live channel's ledger is
valid, so keeping it is always correct; a closed channel's tags are
redelivered by the broker. A key that reports no liveness at all
(not a pika/aio-pika channel) is dropped, as before.
Source code in src/rabbitkit/highload/batch.py
close() -> GroupFlushReport
¶
Close every acker (draining what is approved) and clear the group.
Source code in src/rabbitkit/highload/batch.py
GroupFlushReport
dataclass
¶
Aggregate of one :meth:CoalescingAckerGroup.flush across channels.
Source code in src/rabbitkit/highload/batch.py
ChannelMismatchError
¶
Bases: RuntimeError
A delivery from a different channel was handed to a bound
:class:CoalescingAcker.
Delivery tags are a PER-CHANNEL counter: tag 7 on channel A and tag 7 on
channel B are different messages. Mixing two channels in one ledger makes
a cumulative ack computed from channel A's prefix settle channel B's
messages — silent, wrong, and unrecoverable. Bind the acker (constructor
channel_key= or the first register(..., channel_key=...)) and this
is caught at registration instead.
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
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 | |
Attributes¶
worker_count: int
property
¶
Return the configured worker count.
pending_count: int
property
¶
Number of tasks currently pending/running.
Methods:¶
__init__(config: WorkerConfig | None = None, *, threaded: bool = False) -> None
¶
threaded=True runs handlers on worker threads even when
worker_count is 1 (one dedicated thread instead of inline on the
caller): SyncBroker uses it for ConsumerConfig.processing_timeout,
which needs the I/O thread free while a handler runs.
Source code in src/rabbitkit/concurrency.py
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
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 | |
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.
Deliveries that were prefetched into the pool but are still waiting
for a worker slot are released first: their tasks are cancelled
before the handler starts and each message is nacked with
requeue=True, so the broker can hand it to another consumer at
once instead of this process running it during the grace period.
Then waits up to timeout for in-flight tasks, then cancels the rest and
waits at most _CANCEL_JOIN_TIMEOUT more for them to unwind. A
handler that swallows CancelledError is abandoned (logged) rather
than allowed to hold stop() open past its deadline.
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.
Concurrency semantics, per queue:
worker_count >= 2: a worker pool of that size runs the handlers; prefetch isworker_count * prefetch_per_workerwhenprefetch_per_workeris set.worker_count == 1(the default) creates NO pool, andprefetch_per_workeris ignored. On the async broker every delivery then runs as its own task, so up toprefetch_counthandlers of one queue run concurrently --worker_count=1does not serialize async handlers. Useprefetch_count=1(or a lock in the handler) for one-at-a-time processing. On the sync broker handlers run inline on the I/O thread, one at a time (withConsumerConfig.processing_timeoutset: one at a time on one dedicated handler thread, so the I/O thread can enforce the deadline).
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
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 | |
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.