Scenario: an async endpoint stalls every request
An async endpoint calls a blocking library operation. While it runs, unrelated requests stop progressing even though they are implemented with async def. Adding more coroutine tasks does not reduce the stall.
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: 18 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.
- Build a diagnosis from evidence
- Compare a repair with its trade-offs
- Test the changed behaviour
Follow the evidence.
An async endpoint calls a blocking library operation. While it runs, unrelated requests stop progressing even though they are implemented with async def. Adding more coroutine tasks does not reduce the stall.
Observed evidence
- The blocking operation runs on the event-loop thread.
- A lightweight heartbeat is delayed during the operation.
- The library call does not yield to the event loop.
Investigation sequence
- Separate CPU-bound work from blocking I/O.
- Use loop-lag measurements and stack/profiling evidence to locate the synchronous call.
- Use an async client or bounded thread offload for appropriate I/O; test cancellation and resource ownership.
Challenge the repair
- Add a test that concurrently runs a heartbeat and the adapter without depending on exact timing.
- What happens if the caller times out but the thread keeps running?
Read the incident, not just the error
An event loop lets several waiting operations make progress on one thread. A synchronous call that keeps that thread occupied prevents the loop from choosing another ready task.
Understand first
Use this explanation when unrelated async requests stall together. Know ordinary calls, loops and lists first. The evidence must locate the occupied thread; a large task count alone does not explain lost progress.
Words you will see
- Event loop
- The coordinator that resumes ready asynchronous tasks.
- Yield
- Give control back so another task may run.
- Heartbeat
- A small independent operation used to observe whether progress remains possible.
Read the progress evidence
The incident reports a delayed heartbeat while a synchronous library call runs on the event-loop thread. That supports the hypothesis that the library prevents cooperative progress. A slow database, exhausted connection pool or CPU loop could produce similar symptoms; a stack sample and the location of the call distinguish them.
The program below is a sequential scheduling model. It records which task owns each turn; it creates no asynchronous tasks and measures no elapsed time. The two work turns before the heartbeat represent a period without a scheduling opportunity, not a measured production delay.
Make a reproduction that can challenge the hypothesis
In a supported local CPython lab, coordinate a controlled blocking adapter with events. Hold it until the test has checked whether an independent heartbeat can run. Avoid a test that merely sleeps briefly and hopes the operating system chooses the intended order.
If heartbeat progress also fails after removing the suspected call, investigate another cause rather than declaring the first hypothesis proven. Here the browser-local model only explains the ordering counterexample. It does not reproduce real I/O or prove a repair's speed.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
turns = []Start a new evidence list.
for owner in ['work', 'work', 'heartbeat']:Supply a chosen order, not a scheduler observation.
turns.append(owner)Record each owner in that order.
print(turns.index('heartbeat'))Position two means two model turns preceded the heartbeat.
An async endpoint calls a blocking library operation. While it runs, unrelated requests stop progressing even though they are implemented with async def. Adding more coroutine tasks does not reduce the stall.
Conceptual cause of shared request stalls
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- OccupyA synchronous operation holds the loop thread.
- ExcludeOther ready coroutines cannot resume on that thread.
- ObserveIndependent heartbeat progress is delayed.
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.
Model an earlier opportunity.
Try: Move 'heartbeat' between the two work strings.
Its index becomes one; this changes the chosen model order, not runtime scheduling.
Model additional uninterrupted work.
Try: Insert another 'work' before 'heartbeat'.
The index becomes three because another model turn precedes it.
Before you move on
A heartbeat stalls even when there is only one request. Does that rule out a blocked event loop?
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. A single synchronous call can occupy the loop thread. Request count is not the mechanism; the question is whether control returns to the loop while the call is active.
Investigate before changing code
Choose an execution boundary from the work's behavior. Native asynchronous I/O, blocking I/O and CPU work do not need the same repair.
Understand first
An appropriate async client can yield while waiting. A bounded thread adapter can isolate suitable blocking I/O. CPU-heavy Python work may need a process or native implementation instead of more coroutine wrappers.
Words you will see
- Blocking I/O
- A synchronous call that waits for an external resource while occupying its calling thread.
- Offload
- Run work outside the event-loop thread.
- Capacity
- The maximum number of underlying operations allowed to remain active.
State the policy before the mechanism
The browser model maps declared work categories to plans. An async operation stays on the loop only if its implementation really cooperates. A blocking I/O call is a candidate for bounded thread offload. A CPU calculation needs a separate evaluation of process startup, serialization and native code options.
A conventional GIL-enabled CPython thread is not a general promise of parallel Python CPU throughput. Free-threaded builds and libraries that release the GIL change the analysis. Classify the actual implementation rather than making a universal claim from the word Python.
Account for costs and ownership
Each offload consumes a worker and may retain a connection, request body and result. Limit outstanding work as well as running workers; an unbounded waiting queue can still grow. Decide whether the library client is safe to share across threads.
Use the model to review a routing decision, not to simulate execution. A dictionary lookup expresses three choices with small storage proportional to the policy entries. Real offload latency, resource limits and exception propagation need separate integration tests.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
routes = {'async': 'loop', 'io': 'bounded-thread', 'cpu': 'evaluate-process'}Declare three policy choices.
kind = 'io'Supply the diagnosed category.
plan = routes[kind]Look up a plan; no thread starts.
print(len(routes))There are three policy entries, not three workers.
Separate CPU-bound work from blocking I/O. Use loop-lag measurements and stack/profiling evidence to locate the synchronous call. Use an async client or bounded thread offload for appropriate I/O; test cancellation and resource ownership.
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.
Review the CPU decision.
Try: Change kind to 'cpu'.
The plan becomes evaluate-process, which calls for further evaluation rather than promising a speedup.
Check an unsupported category.
Try: Change kind to 'unknown'.
Lookup raises KeyError rather than silently selecting a potentially unsafe execution plan.
Before you move on
Would routing a long pure-Python calculation to 'bounded-thread' prove better CPU throughput?
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. It changes where the call runs, not the interpreter's CPU execution guarantees. Evaluate processes or native work with real workload measurements and explicit data-transfer costs.
A repair you can explain
asyncio.to_thread runs a synchronous callable in a thread and lets the coroutine await its result. It is an adapter boundary, not a timeout or a worker-cancellation guarantee.
Understand first
This preserved original is a local CPython thread lab. Browser WebAssembly may reject threading; use a supported local Python runtime for the original source. legacy_read returns immediately, so this fixture demonstrates result forwarding, not responsiveness or performance.
Words you will see
- Coroutine
- A resumable computation created by calling an async function.
- Await
- Wait for an awaitable result; other progress depends on whether the operation actually yields.
- Adapter
- A boundary connecting an existing interface to another execution style.
Follow the original source
legacy_read is an ordinary def that returns the string record. main is async; it passes the callable itself to asyncio.to_thread and awaits the result. Calling legacy_read first would run it on the current thread before the adapter could help.
asyncio.run creates and manages a loop for this standalone script. The print occurs after the awaited result arrives. The output record proves that a returned value crossed the boundary in this fixture; because there is no held I/O, it supplies no loop-lag measurement.
Repair the actual incident separately
Replace an appropriate blocking-I/O integration with a well-behaved async client or a bounded adapter. Include library-level timeouts and a shutdown owner for outstanding work. Do not silently substitute a sequential browser fallback for this original program.
The adapter has worker, scheduling and retained-data costs. Verify returned values and exceptions, observe actual active count, and test a heartbeat while the controlled adapter is held. A passing print alone does not establish cancellation safety or the production library's thread safety.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
import asyncioLoad the standard asynchronous coordination library.
return 'record'The synchronous fixture returns immediately without external I/O.
result = await asyncio.to_thread(legacy_read)Pass the callable for thread execution, then await its returned string.
print(result)Display the returned value after awaiting.
asyncio.run(main())Run the standalone coroutine in a managed loop.
The adapter demonstrates thread offload without making a real external call. A production integration must bound concurrent offloads and configure its own I/O timeout.
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.
Change the returned fixture.
Try: Replace 'record' with 'page'.
The local lab prints page; the adapter preserves the returned value.
Check exception propagation locally.
Try: Replace the return with raise ValueError('adapter failed').
The await raises the error; there is no successful record print.
Before you move on
If legacy_read raises ValueError, should the adapter return record as a fallback?
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. Awaiting to_thread propagates that exception. A fabricated successful value would hide the failure. Catch only declared failures at a boundary whose response contract is explicit.
Reproduce lost progress instead of counting tasks
Run a lightweight heartbeat alongside the affected endpoint and observe whether it can progress while the library operation runs. The incident predicts loop lag because the synchronous call occupies the event-loop thread without yielding. More coroutine objects do not create more opportunities to schedule if execution never returns to the loop. Capture a stack or profile at the stall and identify the blocking call before replacing unrelated async functions.
Separate blocking I/O from CPU computation. Waiting inside a synchronous socket or file library differs from a long Python calculation, although both can stall the loop. A controlled reproduction should coordinate when work starts and when it may finish rather than assert an exact elapsed duration. The existing legacy_read fixture returns immediately, so it demonstrates the adapter boundary but does not itself reproduce a slow external operation or establish a real latency improvement.
Explain cooperative progress and the offload boundary
async def creates a coroutine function, not an automatically parallel function. Progress switches when an awaited operation actually yields control. Calling a synchronous function inside the coroutine runs that function on the loop thread unless explicitly moved elsewhere. Even an await expression can complete immediately without meaningful suspension, so reasoning must follow the actual operation rather than count the number of await keywords in the source.
The reference awaits asyncio.to_thread around legacy_read and prints record. Appropriate blocking I/O can run outside the loop while the coroutine waits for its result. The thread still consumes a resource, and its library operation still needs its own timeout. Moving CPU-heavy Python work to a thread may continue to contend under a conventional GIL-enabled runtime; process or native execution can be alternatives with different startup, serialization, and cancellation costs.
Repair with bounded ownership and realistic cancellation
Prefer a well-behaved async client when it fits the integration contract, or put a concurrency cap around thread offloads so a burst cannot queue unbounded work. Determine whether the legacy client is thread-safe and who owns its connections. A shared client that was safe on one event-loop thread may not be safe across several worker threads. Keep resource creation and cleanup aligned with the actual library's ownership rules.
Cancelling the awaiting coroutine does not guarantee that an already running thread stops. If the caller times out, the underlying operation may still finish and may still perform an external side effect. Avoid immediately starting an unlimited replacement for the same work. Use library-level deadlines, stable operation identities where needed, and shutdown policy for outstanding calls. A semaphore is useful only if its permit lifetime accurately represents active work, including any offload that outlives its original waiter.
Verify responsiveness, failure and shutdown separately
Use events to hold a controlled blocking adapter and prove that the event-loop heartbeat progresses before the adapter is released. Assert that returned data and exceptions pass through correctly. Test a concurrency limit by observing active adapter count, not by hoping a short sleep produces a particular schedule. Add cancellation before start, cancellation during execution, and adapter timeout cases, recording whether underlying work remains active after the caller has stopped waiting.
On shutdown, stop accepting new requests, account for outstanding offloads, and apply the documented drain or abandonment policy. Verify that late results do not update a closed resource or produce a success response for a cancelled request. An async fixture does not establish real process-pool behavior, external networking, or safe cancellation of arbitrary native libraries. Report those as separate integration requirements and preserve the original loop-lag reproduction as a regression check.
Transfer question: A timed-out request releases its concurrency permit, but its offloaded thread continues. Why can this defeat the intended bound?
The permit now counts waiting coroutines rather than active blocking operations. Repeated timeouts can release permits and launch replacements while old threads continue consuming connections and performing work. Track actual offload completion separately, retain capacity until it finishes, and configure a library-level timeout that can bound the operation itself. Decide how late results and exceptions are observed during shutdown. Test with an adapter held by an event: cancel its waiter, submit another request, and verify that active operations never exceed the intended limit. Cancellation of a coroutine is not proof of cancellation of its thread.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Recreate the repair independently
Add a test that concurrently runs a heartbeat and the adapter without depending on exact timing. Start from the symptoms and write your own regression assertion before opening the reference.
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: classify an execution plan
Return policy labels only. This browser-local task does not start threads, processes or coroutines.
The contract
- kinds is a list containing only 'async', 'io' and 'cpu'. Return a new list mapping them to 'loop', 'bounded-thread' and 'evaluate-process'.
- Preserve input order and repeated occurrences. Empty input returns a new empty list.
- Do not mutate kinds or perform I/O. Labels are recommendations, not executed concurrency.
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.
- blocking I/O
r = route_work(['io']) assert type(r) is list and r == ['bounded-thread']
- async operation
assert route_work(['async']) == ['loop']
- CPU evaluation
assert route_work(['cpu']) == ['evaluate-process']
- empty ownership
x = [] r = route_work(x) assert type(r) is list and r == [] and r is not x
- order and duplicates
assert route_work(['io', 'async', 'io']) == ['bounded-thread', 'loop', 'bounded-thread']
- input preservation
x = ['cpu', 'io'] r = route_work(x) assert type(r) is list and r == ['evaluate-process', 'bounded-thread'] and x == ['cpu', 'io'] and r is not x
Why is a passing routing task not proof of responsiveness?
It performs only dictionary lookups and O(n) output construction for n categories. No scheduler or blocking call runs. Real responsiveness needs a coordinated local adapter/heartbeat test.
Guided: bounded admission with a remainder
Split request IDs into an admitted prefix and an explicit remainder without running work.
The contract
- requests is a list of strings; capacity is an integer. Negative capacity raises ValueError.
- Return a tuple of two new lists: at most capacity leading IDs, then all remaining IDs. Preserve duplicates and order.
- Empty input and zero capacity are valid. Do not mutate requests; either output must be independently editable.
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.
- normal split
r = admit_prefix(['a', 'b', 'c'], 2) assert type(r) is tuple and r == (['a', 'b'], ['c']) and all(type(x) is list for x in r)
- zero capacity
assert admit_prefix(['a'], 0) == ([], ['a'])
- empty input
r = admit_prefix([], 2) assert type(r) is tuple and r == ([], []) and r[0] is not r[1]
- oversized capacity
assert admit_prefix(['a', 'a'], 5) == (['a', 'a'], [])
- negative capacity
raised = False try: admit_prefix(['a'], -1) except ValueError: raised = True assert raised - ownership
x = ['a', 'b'] r = admit_prefix(x, 1) assert type(r) is tuple and r == (['a'], ['b']) and r[0] is not x and r[1] is not x r[0].append('z') r[1].append('y') assert x == ['a', 'b']
What does this function cost, and what must the caller do with the remainder?
The two slices copy n references in O(n) time and space. The caller must implement a visible reject, bounded wait or handoff policy; the returned remainder is not an unlimited production queue.
Transfer: cancelled waiters still occupy workers
Change admission accounting from caller lifetime to actual operation lifetime.
The contract
- operations is a list of (id, waiter_live, finished) tuples with Boolean flags; limit is a nonnegative integer.
- Return an exact int: max(0, limit minus the number of operations with finished False). Count every occurrence, even if its waiter is cancelled.
- Finished operations consume no slot. Preserve input and perform no real scheduling or cancellation.
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.
- ordinary active work
r = free_slots([('a', True, False)], 3) assert type(r) is int and r == 2 - cancelled waiter
assert free_slots([('a', False, False)], 1) == 0 - completed work
r = free_slots([('a', True, True), ('b', False, True)], 2) assert type(r) is int and r == 2 - empty
r = free_slots([], 4) assert type(r) is int and r == 4
- overflow and zero
r = free_slots([('a', False, False), ('a', True, False)], 1) assert type(r) is int and r == 0 and free_slots([], 0) == 0 - preserve operation evidence
x = [('a', False, False), ('b', True, True)] r = free_slots(x, 3) assert type(r) is int and r == 2 and x == [('a', False, False), ('b', True, True)]
Why did the changed requirement invalidate waiter-based counting?
A timed-out caller can leave a running thread behind. One O(n) scan and O(1) counters model active work without pretending to cancel it. A real supervisor must retain and observe underlying completion.
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 milestoneThe underlying mechanism
Cancelling a coroutine that waits for a thread does not necessarily stop the running thread. Capacity should follow underlying work, not only the lifetime of its waiter.
Understand first
A caller timeout can end the response while work still consumes resources. Releasing a permit too early lets replacements exceed the intended active-operation bound.
Words you will see
- Waiter
- The coroutine waiting for a result.
- Permit
- An accounting token for limited capacity.
- Completion
- The underlying operation has actually stopped running, successfully or otherwise.
Separate two lifetimes
The model starts with one running operation and a live caller. Caller cancellation changes waiting to False but leaves running at one. With capacity one, another operation must not start yet. These assignments model state; they are not a real cancellation experiment.
An awaiter's cancellation may prevent queued work from starting, but it does not forcibly interrupt an arbitrary already-running library call. Establish the exact point at which the adapter started before deciding whether capacity can be released.
Assign a completion owner
A supervisor can retain the running operation, observe its late result or exception and release capacity on actual completion. Configure the library's own deadline. During shutdown, stop admission and decide how to drain or account for operations that outlive callers.
The model's capacity comparison is constant work with a few integer and Boolean values. A real supervisor additionally retains task handles and resources until completion. If cancellation discards every reference, neither a semaphore nor a hopeful timeout describes the real active 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 = 1Allow one underlying operation.
running = 1That capacity is occupied.
waiting = FalseModel the caller ceasing to wait, without decrementing running.
print(running < capacity)No new work fits until actual completion.
Cooperative scheduling progresses at await points of operations that actually yield. A synchronous CPU loop does not become nonblocking merely by being inside async def. Moving CPU-heavy Python work to a thread may still contend under a conventional GIL.
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.
Model real completion.
Try: Set running = 0 after waiting = False.
Admission becomes possible because the underlying count now falls.
Increase the allowed active bound.
Try: Change capacity to 2 while keeping running = 1.
There is room for one more modeled operation, not an unlimited queue.
Before you move on
Capacity is two; two threads are active and both callers cancel. How many replacements fit before either thread finishes?
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
Zero under an actual-active-work bound. Both operations still occupy capacity. The supervisor must observe their completion before allowing replacements.
Alternatives and operational trade-offs
Backpressure means declining or delaying new work when capacity is full. A bounded policy must also describe what happens to queued work and late results.
Understand first
Moving a stall out of the loop can move the failure into memory or worker exhaustion. An explicit admission policy makes that trade-off visible before a burst arrives.
Words you will see
- Backpressure
- Restraining incoming demand when a downstream resource cannot accept more.
- Admission
- The decision to accept work now.
- Queue bound
- A maximum number of operations retained for later work.
Choose a visible overload response
The example models accepted and deferred identifiers without executing any of them. A slice takes the first capacity items; the remaining suffix represents callers that must receive a documented delay or rejection. Keeping that suffix forever would itself be unbounded buffering.
In production, a queue limit, a timeout and a shutdown policy complement a worker limit. Choose reject, wait with a bound, or durable handoff based on whether the work can safely be retried. Avoid claiming an operation failed if it may already be running.
Test policy and integration separately
Policy tests can check zero capacity, repeated IDs and input preservation without a scheduler. The transfer exercise changes the rule: cancelled waiters still consume capacity while their operations remain active. That tests whether lifetime reasoning transfers beyond a simple queue slice.
Slicing n requests takes O(n) total work and extra reference storage for the two output lists. That is a model cost, not a throughput estimate. Verify actual active counts and controlled heartbeat progress separately in the supported local integration lab.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
requests = ['a', 'b', 'c']Supply ordered request identifiers.
capacity = 2Set an admission budget, not a thread pool.
accepted = requests[:capacity]Copy the admitted prefix.
deferred = requests[capacity:]Copy the remainder for an explicit caller policy.
Prefer a well-behaved async library when possible. Thread offload needs a concurrency cap and does not guarantee running code can be forcibly cancelled. CPU workloads may need a process/native implementation, with serialization and cancellation costs.
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.
Model overload.
Try: Set capacity = 0.
accepted becomes empty and deferred retains all three identifiers.
Check duplicate handling.
Try: Change requests to ['a', 'a', 'b'].
Both occurrences of a stay in order; admission does not silently deduplicate.
Before you move on
If capacity is zero, should this model drop the three requests silently?
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. It returns an empty admitted prefix and all requests in the remainder. The caller must implement a visible reject or bounded-wait policy rather than inventing success.
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.