Queues, backpressure and bounded workloads
Keep producers from overwhelming memory and downstream services.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain bound outstanding work
- Apply define completion and shutdown
- Reason about observe the bottleneck
Bound outstanding work
A queue holds waiting work; a worker limit bounds active work. A system needs both limits when incoming work can outpace completion, otherwise waiting items can still grow without bound.
Understand first
A fast producer can overwhelm a slow service even with only two running workers. Know lists and if statements before treating capacity as a policy. Here capacity counts waiting slots only, not the number of items already executing.
Words you will see
- Producer
- The part of a system that submits work.
- Consumer
- The part that takes and processes submitted work.
- Backpressure
- A mechanism that slows or rejects upstream work when downstream capacity is limited.
A worker bound is not a storage bound
The fixture starts with a waiting item a. Item b fills the second slot, so c and d are rejected in arrival order. No consumer runs during this modeled admission step, making the result deterministic. The final True checks a storage invariant, not processing success.
If workers were limited but appends were unrestricted, waiting memory could grow while the same two workers stayed busy. A queue capacity bounds item count, not total bytes: one enormous payload can still exceed a memory budget. Bound payload size separately.
Choose what full means
Reject-new preserves previously admitted items. Waiting propagates pressure but needs a deadline and cancellation policy. Dropping old items may fit telemetry but not payments. The choice changes product behavior and must be stated rather than hidden in a container option.
With capacity zero this reject-new model accepts no items; some queue libraries use maxsize=0 to mean unbounded instead. Read the actual API contract. Browser models do not supply concurrent synchronization or durability. A real queue lab must use an environment supporting its chosen API.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
waiting = ['a']Start with one already-admitted waiting item.
if len(waiting) < capacity:Check admission before appending.
rejected.append(item)Keep overflow visible rather than silently losing it.
print(len(waiting) <= capacity)Verify the planned waiting-slot invariant.
A concurrency limit bounds running work; a queue limit bounds waiting work. Both matter. If producers outpace consumers indefinitely, an unbounded queue consumes unbounded memory even when only a few workers are active.
Conceptual admission boundary, not a live queue meter
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- ArriveAn incoming item asks for a waiting slot.
- AdmitIf fewer than capacity items wait, append in arrival order.
- FullApply an explicit wait, reject or shedding policy instead of growing silently.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Allow another waiting slot.
Try: Set capacity = 3.
a, b and c are kept; only d is rejected.
Start with no waiting items.
Try: Set waiting = [].
b and c are admitted and d is rejected; the incoming order is preserved.
Before you move on
With two waiting slots, two active jobs and both slots occupied, how many jobs are outstanding?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Four: two active plus two waiting. A waiting-capacity bound is not a total-in-system bound.
Define completion and shutdown
Removing an item from a queue is not the same as finishing it. Acknowledgment records completed handling, and shutdown must give every worker a way to exit without abandoning accepted work.
Understand first
A supervisor must not announce completion merely because a worker has taken the last item. Know try/finally first. This fixture keeps two numbers visible: waiting items and admitted items whose handling has not yet been acknowledged.
Words you will see
- Acknowledgment
- A signal that one consumed item's handling is accounted for.
- Unfinished work
- Admitted work that has not yet received its completion acknowledgment.
- Sentinel
- A distinguished queue item used by an agreed shutdown protocol to ask a worker to exit.
Track the lifetime beyond get
unfinished starts at one. pop removes invoice from waiting, but it does not finish the uppercase operation. The first print is therefore 0 1. finally decrements unfinished after the attempt and the final print is 0 0.
In asyncio.Queue, task_done acknowledges a consumed item and join waits until the unfinished count reaches zero. Each successful get needs exactly one appropriate acknowledgment. task_done without matching work raises ValueError; missing acknowledgments can leave join waiting.
Define what acknowledgment promises
Acknowledgment in finally can mean the processing attempt was accounted for, even when it raised. It does not prove a business action succeeded. If failed work must retry, record or requeue it according to a bounded failure policy before announcing completion.
A sentinel protocol must cover every worker, including whether the sentinel itself is acknowledged. Cancellation and shutdown APIs are alternatives with runtime-version differences. A local Python queue is not durable delivery; a process crash can lose both queued and active items.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
unfinished = len(waiting)Count one admitted, unacknowledged item.
item = waiting.pop(0)Remove the item without marking it completed.
print(len(waiting), unfinished)The two prints distinguish 0 1 from 0 0.
unfinished -= 1Account for the attempt after its processing region.
For an asyncio.Queue, task_done acknowledges one consumed item and join waits for acknowledged work. Put acknowledgments in a finally block where appropriate. A sentinel, cancellation or explicit shutdown policy must cover every worker without silently losing queued work.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Skip the visible work but keep cleanup.
Try: Replace result = item.upper() with result = 'skipped'.
The acknowledgment still occurs, illustrating that accounting does not prove business success.
Make processing fail visibly.
Try: Replace result = item.upper() with raise ValueError('demo').
finally still decrements, but the error is visible and the final print is not reached.
Before you move on
If three items were removed but only two acknowledged, may join be treated as complete because the queue is empty?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. One item remains unfinished even with zero waiting items. The missing acknowledgment must be resolved by the owning worker's policy.
Acknowledge every consumed item
The bounded asyncio queue sample owns one item from put through task_done. join observes acknowledgments, not just removal, and the final empty flag says only that no item is waiting.
Understand first
Keep the original real asyncio.Queue example to connect the state model to an API. It requires an asyncio-compatible Python runtime, not OS threads or processes. There is only one item and one consumer, so no timing assumptions are needed.
Words you will see
- maxsize
- The maximum waiting-item count for this queue when positive; zero or less means unbounded in asyncio.Queue.
- task_done
- The queue operation that acknowledges one previously consumed item.
- join
- The queue wait that completes when its unfinished-item count is zero.
Follow one owned item
put admits integer three into a queue with two waiting slots. get removes it and returns its value. The try block prints six, and finally calls task_done whether processing succeeds or fails. join can then finish because the one admitted item was acknowledged.
The final True reports empty waiting storage after that lifecycle. It is not itself proof of processing; join is the accounting wait. This queue is designed for async tasks on one loop, not as a general thread-safe or cross-process queue.
Do not turn capacity into a deadlock
Awaited put waits when a positive-size queue is full. If the same coroutine fills it and waits on another put before any consumer can run, the program can wait forever. Arrange consumer lifetimes and bounded shutdown before expanding this fixture.
An empty queue's get waits; do not invent a default item. maxsize=0 is unbounded, unlike the zero-capacity reject-new exercise policy. A real service needs failure handling, payload limits and explicit shutdown in addition to this minimal successful example.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
queue = asyncio.Queue(maxsize=2)Allow up to two waiting items.
value = await queue.get()Take the admitted three, leaving it unfinished.
queue.task_done()Acknowledge the processing attempt in finally.
await queue.join()Wait for all admitted items to be acknowledged before reporting empty.
The bounded queue has one produced and one acknowledged item. Acknowledgment represents processing completion, not just removal from the queue.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Use a different value.
Try: Change await queue.put(3) to await queue.put(5).
The first output becomes 10 and the final empty flag stays True.
Use one waiting slot.
Try: Change maxsize=2 to maxsize=1.
Output stays 6 and True because this fixture never holds two waiting items.
Before you move on
Would changing maxsize to one change the original output, and why?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Only one item is waiting at any time. It still prints 6 then True; a smaller bound matters only when arrivals would exceed it.
Where this idea earns its place
Backpressure connects a producer's admission rate to available processing capacity. Limiting active workers alone does not bound the number of waiting jobs. A fast producer can fill memory with queued records while every worker remains within its nominal concurrency limit.
Follow the mechanism step by step
A bounded queue makes put wait when capacity is exhausted. get removes an item for processing, while task_done acknowledges completion of one retrieved item; join waits for acknowledged work. These are separate transitions. Removing an item is not proof that its side effect completed successfully.
Work through a concrete application
Design a producer, a worker and a shutdown signal together. In the single-worker example, enqueue values, then a sentinel, acknowledge each retrieval in finally and wait for join inside a scoped task group. For several workers, provide the correct number or form of shutdown signals and decide whether result order must match input order.
Failure cases and misleading shortcuts
Forgetting task_done can make join wait indefinitely. Acknowledging before work finishes can falsely report completion. A failed worker can leave the producer blocked on a full queue unless the group propagates failure and cancels related work. A local queue also cannot recover accepted work after process loss.
Cost, ownership and alternatives
Choose what happens when full: wait, reject, shed optional work or persist to a durable broker. Bound item size as well as item count, since one oversized message can violate the memory budget. Increasing workers may overload a database or API instead of improving end-to-end throughput.
Verify the contract
Test empty work, a full queue, a worker exception, producer failure and cancellation. Assert that success is reported only after the required work is acknowledged. Use coordinated events to hold a worker at a known point and prove the admission bound without depending on machine timing.
Transfer question: Which metrics reveal whether adding workers is helping?
Measure queue depth and oldest-item age alongside service time, error/retry rate and downstream saturation. A lower local queue depth accompanied by more database errors is not necessarily an improvement. Include rejected or dropped work in the operational report.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Acknowledge every consumed item
Without copying the worked code, reproduce its observable contract: The bounded queue has one produced and one acknowledged item. Acknowledgment represents processing completion, not just removal from the queue. Then change one boundary input and explain the result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: reject overflow without losing accepted work
Implement admit_work(waiting, incoming, capacity) with a reject-new policy, including an explicit zero-slot boundary.
The contract
- waiting and incoming are finite lists of string items; repeats and empty strings are allowed. capacity is an exact integer. Raise ValueError if capacity < 0 or len(waiting) > capacity.
- Return an exact tuple (kept, rejected) of fresh exact lists. Begin kept with waiting. Append incoming items in arrival order while len(kept) < capacity; otherwise append to rejected.
- Do not mutate either input. Capacity counts waiting slots only. Zero capacity admits no new items; this deliberately differs from asyncio.Queue(maxsize=0), which is unbounded.
- Empty inputs return two separate empty lists. No consumer runs during this deterministic admission step; it is not a concurrent or durable queue.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- fill then reject
out = admit_work(['a'], ['b', 'c'], 2) assert type(out) is tuple and out == (['a', 'b'], ['c']) and all(type(part) is list for part in out)
- zero capacity rejects all new items
out = admit_work([], ['a', 'a', ''], 0) assert type(out) is tuple and out == ([], ['a', 'a', ''])
- empty lists have separate ownership
out = admit_work([], [], 0) assert type(out) is tuple and out == ([], []) and type(out[0]) is list and type(out[1]) is list and out[0] is not out[1] out[0].append('a') assert out[1] == [] - duplicates and exact full occupancy
out = admit_work(['a'], ['a', '', 'b'], 3) assert type(out) is tuple and out == (['a', 'a', ''], ['b'])
- invalid capacity rejects before processing
for waiting, capacity in [([], -1), (['a', 'b'], 1)]: raised = False try: admit_work(waiting, [], capacity) except ValueError: raised = True assert raised - preserve inputs and own both outputs
waiting = ['a'] incoming = ['b', 'c'] out = admit_work(waiting, incoming, 2) assert type(out) is tuple and out == (['a', 'b'], ['c']) and out[0] is not waiting and out[1] is not incoming out[0].append('x') out[1].append('y') assert waiting == ['a'] and incoming == ['b', 'c'] and admit_work(waiting, incoming, 2) == (['a', 'b'], ['c'])
Does capacity two imply only two total outstanding jobs?
No. Active jobs are not counted by this waiting-only policy. For w existing and n incoming items, it takes O(w + n) time and O(w + n) result space; bounded item count also does not bound payload bytes.
Guided: distinguish waiting from in-flight
Implement queue_counts(events), maintaining waiting and active-but-unacknowledged counts separately.
The contract
- events is a finite list whose entries are exactly 'put', 'get' or 'done'. Other values are outside this domain. Start with zero waiting and zero in-flight.
- put adds one waiting item. get requires waiting > 0, then moves one from waiting to in-flight. done requires in-flight > 0, then removes one in-flight item.
- Raise ValueError on an impossible get or done at its point in the sequence. Return an exact tuple (waiting, in_flight) of exact ints after a valid sequence. Empty returns (0, 0).
- Do not mutate events. This is an aggregate policy model without identities or threads. Acknowledgment records handling, not guaranteed business success or durable delivery.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- removal is not completion
out = queue_counts(['put', 'get']) assert type(out) is tuple and out == (0, 1) and all(type(value) is int for value in out)
- empty aggregate
out = queue_counts([]) assert type(out) is tuple and out == (0, 0) and all(type(value) is int for value in out)
- repeated puts gets and done
out = queue_counts(['put', 'put', 'get', 'get', 'done', 'put']) assert type(out) is tuple and out == (1, 1)
- one full lifecycle
out = queue_counts(['put', 'get', 'done', 'put', 'get', 'done']) assert type(out) is tuple and out == (0, 0)
- invalid get cannot borrow future put
raised = False try: queue_counts(['get', 'put']) except ValueError: raised = True assert raised - invalid done and caller ownership
for events in [['put', 'done'], ['put', 'get', 'done', 'done']]: raised = False try: queue_counts(events) except ValueError: raised = True assert raised events = ['put', 'get', 'done', 'put'] out = queue_counts(events) assert type(out) is tuple and out == (1, 0) and events == ['put', 'get', 'done', 'put']
Can (0, 2) be described as fully drained?
No. It has no waiting items but two unacknowledged processing attempts. The reducer takes O(n) time for n events and O(1) counter space under bounded-integer assumptions; it cannot detect which specific item was acknowledged.
Transfer: replace pending status while full
Implement coalesce_status(pending, incoming, capacity). Unlike reject-new items, an existing key's latest status must still be accepted when every slot is occupied.
The contract
- pending is a finite list of unique (string key, exact integer value) tuples. incoming has the same tuple shape but may repeat keys. capacity is an exact integer; reject negative capacity or len(pending) > capacity with ValueError.
- Return an exact tuple (kept, rejected) of fresh exact lists containing exact two-element tuples. Keep at most capacity distinct keys, in first-admitted order.
- For an existing key, replace its pending value without moving its position, even when full. Admit a new key only if a slot remains; otherwise append that incoming tuple to rejected in arrival order. Rejected keys do not become pending.
- Do not mutate either input. Zero capacity rejects every incoming item if pending is empty. Empty valid inputs return separate empty lists. Values are immutable; no deep copy is needed.
- This intentionally loses superseded values, so it fits status snapshots rather than payments. It is a deterministic overload model, not synchronized or durable storage.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- replace existing at full capacity
out = coalesce_status([('a', 1), ('b', 2)], [('a', 3), ('c', 4)], 2) assert type(out) is tuple and out == ([('a', 3), ('b', 2)], [('c', 4)]) and all(type(part) is list for part in out) and all(type(pair) is tuple for part in out for pair in part) - empty results are independently owned
out = coalesce_status([], [], 0) assert type(out) is tuple and out == ([], []) and type(out[0]) is list and type(out[1]) is list and out[0] is not out[1]
- zero capacity records every rejection
out = coalesce_status([], [('a', 1), ('a', 2)], 0) assert type(out) is tuple and out == ([], [('a', 1), ('a', 2)]) - latest value preserves first position
out = coalesce_status([('z', 1)], [('a', 2), ('z', 3), ('a', 4), ('z', 5)], 2) assert type(out) is tuple and out == ([('z', 5), ('a', 4)], []) - invalid initial capacity rejects
for pending, capacity in [([], -1), ([('a', 1), ('b', 2)], 1)]: raised = False try: coalesce_status(pending, [], capacity) except ValueError: raised = True assert raised - source preservation and result independence
pending = [('b', 1)] incoming = [('a', 2), ('b', 0), ('c', 3)] out = coalesce_status(pending, incoming, 2) assert type(out) is tuple and out == ([('b', 0), ('a', 2)], [('c', 3)]) and out[0] is not pending and out[1] is not incoming out[0].append(('x', 9)) out[1].append(('y', 9)) assert pending == [('b', 1)] and incoming == [('a', 2), ('b', 0), ('c', 3)] assert coalesce_status(pending, incoming, 2) == ([('b', 0), ('a', 2)], [('c', 3)])
What changed from a reject-new FIFO item policy?
Identity now matters: existing keys replace values without using new slots, while rejected new keys stay absent. Old status history is intentionally lost. With p pending and n incoming records this uses O(p + n) expected time and O(p + n) result space under ordinary dict assumptions, including rejections.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneBackpressure is a product choice
When a queue is full, loss and delay become product decisions. Keeping only the latest update for a key can be correct for status displays, but silently replacing an order or payment would change its meaning.
Understand first
A dashboard may need the most recent reading per device rather than every intermediate reading. Understand dictionary key uniqueness and insertion order first. This overload policy intentionally loses old values for an existing key and must not be used where every event matters.
Words you will see
- Coalescing
- Combining repeated pending updates under one identity, here by retaining only the latest value.
- Reject-new
- An overload policy that refuses new identities when capacity is full.
- Durability
- Retention that survives specified failures, unlike ordinary in-memory queue state.
Update without changing the slot count
Both waiting slots are occupied initially. sensor-a is already pending, so replacing ten with eleven needs no new key and is accepted. sensor-c would require a third key and is rejected. Updating sensor-a leaves its first-insertion position unchanged.
The rejected list makes the loss decision visible to the caller. A full deque with automatic eviction would implement a different policy. A plain dictionary is useful for this bounded model but does not add synchronization when several producers mutate it.
Match the policy to the promise
Waiting may fit a lossless request path if deadlines and cancellation are explicit. Rejecting can let callers choose retry or fail fast. Durable brokers can add recovery guarantees, but persistence and acknowledgment configuration must be understood rather than assumed.
Coalescing is inappropriate when repeated events have distinct side effects, such as charging twice for two separate purchases. Zero pending capacity can reject all new keys in this model. Define whether updates to existing keys still count as admitted, and keep byte-size limits separate from key count.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
capacity = 2Bound the number of distinct pending keys.
if key in pending or len(pending) < capacity:Permit a replacement even at full occupancy.
pending[key] = valueKeep the latest value without moving an existing key.
rejected.append((key, value))Report the new key that cannot be admitted.
When full, a producer can wait, reject, shed low-priority work or write to a durable broker. Choose according to latency and loss requirements. A local Python queue is not durable and cannot recover lost work after a process crash.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Allow the new sensor.
Try: Set capacity = 3.
sensor-c is appended as a third key and rejected is empty.
Replace the same sensor twice.
Try: Add ('sensor-a', 12) to the incoming list.
sensor-a ends at 12 and remains first; no third slot was needed.
Before you move on
If sensor-b receives values 21 then 22 while full, how many slots does it use and which value survives?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
One slot, retaining 22 in sensor-b's original position. Both intermediate history and value 21 are absent unless recorded elsewhere.
Observe the bottleneck
Queue depth is only one signal. The oldest waiting age, rejection count, service time and retries explain different bottlenecks. Retrying faster can amplify an outage instead of fixing it.
Understand first
A queue of two items may be healthy if they just arrived or unhealthy if one has waited for hours. Start with a defined observation time rather than sleeping in a test. Here ticks are nonnegative integers from one consistent clock and arrival ticks do not exceed now.
Words you will see
- Oldest-item age
- Time since the earliest still-waiting item was admitted.
- Retry amplification
- Extra load created by repeated attempts while the original cause of failure remains.
- Jitter
- A deliberately varied retry delay that reduces synchronized retry bursts.
Measure state and time separately
At tick twelve, arrivals at four and nine give depth two and oldest age eight. Neither number tells how long a completed item took to process; service time needs start and finish observations. The default zero defines the empty-waiting result without calling max on an empty sequence.
The retry list is a fixed schedule, not randomness or actual sleeping. No retry is due at twelve. At seventeen, the inclusive boundary permits thirteen and seventeen but not twenty-one. A dispatcher must also apply capacity and per-job deadline rules before starting due retries.
Do not cure downstream overload with more load
Increasing workers may exceed a database's or API's safe concurrency and make service time worse. Repeated immediate retries can add more arrivals exactly when capacity is lowest. Use bounded attempts, backoff, jitter and deadlines according to the external contract.
Measure queue depth, oldest age, rejection count and service-time distributions together in a real local or deployed lab. This deterministic clock model does not measure throughput or prove a retry policy safe. An in-memory schedule also loses its pending retries on a process crash unless another system persists them.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
now = 12Choose a controlled observation tick, not wall-clock time.
oldest_age = max((now - tick for tick in arrived), default=0)Find eight as the largest elapsed wait, with an empty default.
print(len(arrived), oldest_age)Report independent depth and age signals.
now = 17Advance the model so the inclusive retry boundary can be observed.
Measure queue depth, oldest-item age, service time, rejection count and retry amplification. Increasing workers can overload a database or API. Introduce jittered retries and deadlines so an outage does not generate an even larger work backlog.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Observe an empty waiting queue.
Try: Set arrived = [].
Depth and oldest age are both zero by the stated empty policy.
Move the first observation later.
Try: Set the first now = 15.
Oldest age becomes eleven and retry tick thirteen becomes eligible at that observation.
Before you move on
Two queues each hold one item; one arrived at tick 2 and the other at tick 19. At tick 20, are their waiting states equivalent?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Their depths are equal, but their oldest ages are eighteen and one. The long wait may indicate stalled processing despite low depth.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.