FastAPI / Intermediate: application integration and security / Lesson 14
Streaming responses and client disconnects
Stream a bounded response while managing producer resources, cancellation and partial failures.
On this page
Lesson goals
- Explain when streaming differs from a buffered response.
- Build an illustrative streaming response with cleanup.
- Test partial delivery, disconnect and authorization boundaries.
- Design streaming representations that expose completion and truncation.
- Own source cleanup, bounded resources, and disconnect tests at the correct boundary.
Choose a streaming contract
Streaming can return response body chunks as they become available instead of constructing the entire body first. It is useful for large generated content, but it does not remove backpressure, timeouts or resource limits. Define the media type, expected completion and client behavior if the stream ends early. A partially transmitted response cannot always be replaced by a fresh JSON error after headers have already been sent.
Create a bounded producer
The illustrative generator yields three synthetic lines and then finishes. StreamingResponse consumes the iterator and sends a response with the specified media type. In a real application the generator may own a cursor, file or upstream response; bound the amount and duration of work, and avoid blocking the event loop with synchronous network or file operations inside async code. This snippet does not establish production throughput.
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
@app.get('/lines')
def lines():
def generate():
for number in range(3):
yield f'{number}\n'
return StreamingResponse(generate(), media_type='text/plain')
The generator is bounded and illustrative. Server, proxy and client behavior must be tested separately.
Release owned resources
A stream can end normally, fail while producing data or be cancelled when a client disconnects. Put cleanup in a finally block for resources owned by the producer, and use the resource’s appropriate close method. The second fragment is schematic and assumes an application-defined async source. Verify actual cancellation and cleanup behavior with the chosen ASGI server and client; a local test may buffer the response.
async def generate():
source = await open_source()
try:
async for chunk in source:
yield chunk
finally:
await source.aclose()
open_source is application-specific and must return an async iterator with aclose. The finally block expresses resource ownership.
Authorize before starting
Authenticate and authorize the requested resource before beginning the stream, and apply tenant filters to the data source. Once headers or body bytes have been sent, changing the status may no longer be possible. Do not put secrets in chunks or failure logs. For sensitive exports, define content disposition and retention, and consider the effect of client retries on data generation and access checks.
Test the complete lifecycle
Use a synthetic data source to test an empty result, complete stream and an exception during production. Verify ordering, content type and cleanup, then test a client disconnect in an integration environment that actually streams. Measure memory, duration and concurrent connections with representative data. A passing buffered client test verifies the returned content but does not prove proxy buffering, network backpressure or disconnect propagation.
Understand a response as a sequence
StreamingResponse can consume an iterator or async iterator and send its chunks as a response without first constructing the entire body in application memory. The client receives one HTTP response whose body arrives over time; an application chunk is not necessarily preserved as a network packet or as one client read. A proxy, server, transport, or client can buffer or combine data. Define the representation and framing that the client can parse independently of incidental chunk boundaries, such as a documented line-delimited format or a length-aware protocol.
Perform authentication, authorization, and checks that must change the status before starting the stream where possible. Once headers and body bytes have been sent, a later exception cannot reliably replace the already-started response with a new JSON 500. A stream that yields two records and then loses its source can therefore look like a successful status with incomplete content. Specify how a client detects truncation, such as an application-level completion record, count, checksum, or other protocol-appropriate signal, and test the actual contract.
Keep resources alive for their actual use
A stream may continue consuming its source after the route function returns. A file, cursor, database session, or external response used by the iterator must remain valid for that consumption and be closed when it ends. Put acquisition and cleanup in an explicit generator or context-managed lifecycle appropriate to the library and framework version. A try/finally around the yield sequence can express cleanup for normal completion, source failure, and cancellation when the iterator is properly closed. Verify the behavior with the selected server and dependency scope rather than assuming every disconnect is delivered identically.
Avoid holding a database transaction and scarce connection for an unnecessarily slow client. Consider a bounded export job, temporary artifact, pagination, or another design when long-lived cursors would exhaust the pool. Each alternative has its own authorization, storage, expiration, and recovery requirements. Do not pass a request-owned session to a background worker beyond its supported lifetime. A resource closed before iteration begins can fail immediately; a resource never closed after an interrupted stream can leak capacity.
Treat disconnect and cancellation as operational events
A client can stop reading or disconnect while the server is producing data. The application should release its source and avoid continuing expensive work unnecessarily, but cancellation propagation depends on the ASGI server, framework, proxy buffering, and source implementation. A synchronous blocking iterator may not stop immediately just because an async task is cancelled; check the library’s semantics and introduce cooperative cancellation or bounded operations where possible. Cleanup must tolerate partial progress and must not assume that every intended chunk was delivered.
A disconnect does not automatically undo a side effect already performed by the source, nor does it prove what the client received. Keep streaming sources read-only when possible and separate external mutations into explicit, idempotent workflows. Log safe categories and correlation IDs, not sensitive records or credentials. Define retry behavior carefully: restarting a stream from the beginning can duplicate already processed records unless the consumer has a checkpoint or idempotent processing strategy.
Control slow consumers and resource budgets
Streaming reduces the need to hold a complete representation in one application buffer, but it does not by itself bound total memory, duration, database connections, or work queued elsewhere. A fast producer and slow consumer can accumulate buffered data at multiple layers. Choose bounded queues, chunk sizes, timeouts, maximum export size, and concurrent-stream limits based on the resources they protect. Measure application, proxy, and client buffering rather than assuming a yield maps directly to immediate delivery.
A per-process concurrency limit is not necessarily global across multiple workers. Long-lived streams can occupy a limited connection pool and block ordinary requests. Use admission control and explicit overload behavior, and monitor active streams, duration, source errors, and cleanup failures. Avoid keeping locks open while waiting for a slow network consumer. If a stream cannot complete within a safe budget, an asynchronous export artifact with a status endpoint may be more appropriate, but acceptance of that job still does not mean the artifact is ready.
Test truncation and cleanup at the right boundary
An in-process client can verify a complete synthetic stream, its media type, and the expected sequence of bytes as observed by that client. It may buffer the whole response and therefore cannot by itself prove real network pacing, proxy behavior, or disconnect propagation. Use a controlled streaming integration client and source to stop reading early, then assert that source cleanup occurs. Repeat through the relevant isolated proxy and server configuration when buffering or disconnect handling affects the deployment.
Inject a source failure after two synthetic records and verify the documented incomplete-output signal or client detection rule. Check that the source is closed and that logs contain a safe failure category rather than raw records. Test a successful control with the expected completion marker and a bounded timeout so the test cannot hang indefinitely. A 200 status alone is not evidence that the entire body arrived. These fragments are illustrative and assume named application fixtures; they have not been run against production data or a real network.
20 worked examples
1. Simple byte iterator
Problem: Return a synthetic stream from an iterator.
- The iterator yields two byte strings as response content.
- A complete consumer observes their concatenated body.
def chunks():
yield b"alpha\n"
yield b"beta\n"
@app.get("/export")
def export():
return StreamingResponse(chunks(), media_type="text/plain")
# complete body: b"alpha\nbeta\n"
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The complete body is alpha and beta on separate lines.
Why this result follows: StreamingResponse consumes the supplied iterator over time.
2. Async iterator
Problem: Yield records from an asynchronous source.
- The asynchronous iterator yields one record and then cooperatively suspends.
- It resumes and yields the second record for a complete response.
async def chunks():
yield b"one\n"
await asyncio.sleep(0)
yield b"two\n"
return StreamingResponse(chunks(), media_type="text/plain")
# complete body: b"one\ntwo\n"
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The complete body contains one and two on separate lines.
Why this result follows: StreamingResponse supports an async iterator as its content source.
3. Chunk boundaries are not framing
Problem: Parse lines even when reads are combined.
- The transport or client combines two application chunks into one read.
- The line parser uses newline delimiters rather than assuming one record per read.
server yields: b"a\n", b"b\n"
client read: b"a\nb\n"
parser records: ["a", "b"]
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The client recovers two records a and b.
Why this result follows: Application framing must survive arbitrary transport chunking.
4. Authorize before streaming
Problem: Deny a protected export before emitting bytes.
- The policy checks the verified user before creating the successful response.
- A denied user receives the explicit error without consuming protected chunks.
@app.get("/export")
def export(user: Annotated[User, Depends(current_user)]):
if not may_export(user): raise HTTPException(status_code=403)
return StreamingResponse(chunks(), media_type="text/plain")
# denied user -> 403 before chunks are consumed
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The fixture returns 403 and emits no export body.
Why this result follows: Early authorization preserves a meaningful denial status.
5. Failure after two records
Problem: Interpret a source failure after response start.
- The response status and two records have already been sent.
- The source fails before the protocol’s expected completion marker.
sent status: 200
sent records: row-1, row-2
source: raises before completion marker
client: incomplete stream
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The client detects incomplete output despite status 200.
Why this result follows: A later source failure cannot reliably replace an already-started response.
6. Completion marker
Problem: Provide a parseable success signal.
- The producer emits two records followed by a documented final marker.
- The client checks both marker presence and the expected record count.
record: {"id":1}
record: {"id":2}
final: {"complete":true,"count":2}
client: validates count and final marker
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The client can distinguish this complete fixture from a truncated one.
Why this result follows: An application-level completion contract supplies evidence beyond HTTP status.
7. Missing completion marker
Problem: Detect truncation in a line-delimited export.
- The client receives two valid records.
- The documented final completion record never arrives.
received: {"id":1}\n{"id":2}\n
expected final record: {"complete":true}
client result: incomplete
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The client marks the export incomplete.
Why this result follows: A valid prefix does not establish full stream completion.
8. File lifetime
Problem: Keep a file open while its iterator yields.
- The generator opens the file when iteration begins.
- The context manager keeps it open during reads and closes it when iteration exits.
def file_chunks(path):
with open(path, "rb") as source:
while chunk := source.read(4096):
yield chunk
return StreamingResponse(file_chunks("synthetic.txt"))
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: A completed or properly closed iterator releases the file.
Why this result follows: Resource ownership surrounds the actual consumption period.
9. Premature resource closure
Problem: Diagnose a file closed before consumption.
- The with block exits before the response consumes the iterator.
- The iterator then attempts to read from a closed file.
with open("synthetic.txt", "rb") as source:
iterator = iter(lambda: source.read(4096), b"")
return StreamingResponse(iterator)
# source is closed when response later iterates
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: Streaming fails rather than delivering the intended file.
Why this result follows: The resource lifetime ended before response iteration.
10. Generator cleanup
Problem: Release a source after normal iteration.
- The source is used while the generator is active.
- The finally block runs when the iterator finishes or is properly closed.
def chunks(source):
try:
yield source.read(4)
yield source.read(4)
finally:
source.close()
# consume and close iterator -> source.close() called
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The synthetic source records a close call.
Why this result follows: Cleanup is attached to the source-owning generator.
11. Failure cleanup
Problem: Release a cursor after a source exception.
- Two synthetic records are yielded before the deliberate exception.
- The generator exits through finally and closes the cursor.
def rows(cursor):
try:
yield cursor.next()
yield cursor.next()
raise RuntimeError("synthetic source failure")
finally:
cursor.close()
# failure -> close recorded
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The source failure occurs and cursor cleanup is attempted.
Why this result follows: The cleanup block covers exceptional generator exit.
12. Disconnect integration test
Problem: Observe cleanup after a real early stop.
- The integration client stops reading before the source completes.
- The controlled server and source expose whether disconnect leads to cleanup.
controlled server + streaming client + fake source
client reads first record, then disconnects
assert source.closed within bounded timeout
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The test passes only when the source closes within the bound.
Why this result follows: A network-level fixture can exercise disconnect propagation.
13. Buffered client limitation
Problem: Avoid claiming disconnect behavior from full buffering.
- The in-process client finishes the response rather than dropping the connection early.
- It does not exercise how a real server and proxy propagate a disconnect.
in-process client: receives complete buffered body
real proxy: may buffer independently
claim: disconnect cleanup verified -> unsupported
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The fixture cannot establish the disconnect-cleanup claim.
Why this result follows: Evidence is limited to the transport and behavior actually tested.
14. Slow consumer backlog
Problem: Track buffering between producer and consumer.
- The producer supplies records faster than the consumer removes them.
- An unbounded queue retains the difference over time.
producer: 100 records/second
consumer: 10 records/second
unbounded intermediate queue: backlog grows
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The backlog and its memory use can grow.
Why this result follows: Streaming alone does not bound intermediate buffering.
15. Bounded stream queue
Problem: Apply backpressure at a finite queue.
- The queue cannot retain more than five chunks in this fixture.
- The producer waits when full until the consumer frees capacity.
queue capacity: 5 chunks
queue full: producer awaits capacity
consumer removes one chunk -> producer can continue
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The queue remains bounded at five chunks.
Why this result follows: A bounded queue limits this particular buffer.
16. Connection pool pressure
Problem: Count long-lived streaming database connections in use.
- Each active cursor stream holds one connection in the synthetic fixture.
- All four pool connections are occupied before the ordinary query arrives.
database pool: 4 connections
active cursor streams: 4
new ordinary query: waits for a connection
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The ordinary query waits for pool capacity.
Why this result follows: Slow streams can consume scarce downstream resources.
17. Per-worker stream limit
Problem: Calculate the combined local stream capacity.
- Each process enforces its own independent limit.
- Three processes can each admit two streams simultaneously.
worker processes: 3
per-worker stream limit: 2
possible active streams across workers: 6
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: Up to six active streams are possible in total.
Why this result follows: A process-local limit is not a global limit.
18. Client retry and duplicates
Problem: Resume processing without repeating a recorded effect.
- The restarted stream repeats the records delivered before disconnect.
- The consumer uses stable IDs and its checkpoint to avoid reapplying those records.
first stream: records 1, 2 processed; disconnect
retry: records 1, 2, 3
consumer checkpoint: IDs 1 and 2 already processed
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: Only record 3 produces a new effect in the fixture.
Why this result follows: Retry-safe processing needs an explicit checkpoint or idempotency design.
19. Cancellation and synchronous source
Problem: Avoid assuming a blocking read stops instantly.
- Cancellation stops the coroutine’s wait in the synthetic trace.
- A blocking function already running in a worker thread may keep running.
async task: cancelled while waiting on worker-thread read
synchronous source read: may continue
cleanup: coordinated after read returns
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: The source may continue work briefly after cancellation.
Why this result follows: Cancelling an await does not guarantee immediate thread termination.
20. Safe failure logging
Problem: Record a stream error without copying records.
- The log preserves a reviewed failure category and correlation identifier.
- It does not include the protected record values or credentials.
source error after record 2
log: {"event":"stream_source_failed","request_id":"req-8"}
raw record content: omitted
Illustrative streaming fragment or synthetic trace; app, source and isolated transport are assumed.
Expected result: Operators can correlate the failure without logging raw content.
Why this result follows: Allowlisted diagnostic fields reduce accidental disclosure of protected data.
Common errors and fixes
A failed stream is reported as a normal complete export
- Why it happens
- The client treated end of connection as proof of completeness.
- How to fix it
- Define a completion signal or independently verifiable export contract.
- Prevent it next time
- Test a producer failure after initial bytes.
A cursor remains open after disconnect
- Why it happens
- Resource cleanup depended only on normal completion.
- How to fix it
- Close the owned resource in a finally block.
- Prevent it next time
- Test cancellation with the actual server and driver.
A stream leaks another tenant’s data
- Why it happens
- Authorization occurred after streaming started or filtering was absent.
- How to fix it
- Authorize and scope the source before returning the response.
- Prevent it next time
- Test allowed and denied users with synthetic records.
20 practice exercises
1. A database cursor raises after two chunks. Can the server always replace the response with JSON 500?
Show hint
Determine whether the response has already started before the cursor fails.
Show worked solution
No. Headers and bytes may already have been sent. Define how the client detects incomplete output, release the cursor, and log a safe failure category. Test the chosen protocol and server.
No: after headers or bytes have been sent, the server cannot reliably replace that response with a fresh JSON 500. Define how the client detects incomplete output, close the cursor, and log a safe failure category; test the chosen protocol and server.
Check your solution
- The client detects the missing completion signal or other truncation.
- The cursor cleanup runs after the source failure.
2. How would you test disconnect cleanup?
Show hint
Exercise an actual early stop at the relevant transport boundary.
Show worked solution
Use a controlled streaming integration client and source, stop reading early, and assert that the source cleanup runs. Repeat through relevant proxy infrastructure because a buffered in-process client may not propagate the disconnect.
Use a controlled streaming integration client and source, stop reading after an initial chunk, and assert the source cleanup within a bounded time. Repeat through the relevant isolated proxy because buffering can change disconnect propagation.
Check your solution
- The client disconnects before full consumption.
- The source cleanup is observed within the bound.
3. A newline-framed stream yields b"ab", b"c\nd", and b"e\n" in that order. Derive the complete body and records.
Show hint
Yield boundaries do not define record boundaries.
Show worked solution
Concatenate the yielded bytes in order to get b"abc\nde\n". Splitting on the documented newline delimiter produces records abc and de. The first record spans two yields, and the second begins in the second yield.
Check your solution
- The complete body is b"abc\nde\n".
- The records are abc and de.
4. A client receives b"red\nb" then b"lue\n" from a newline-framed stream. Describe incremental parsing and the state after each read.
Show hint
Keep the incomplete suffix until more bytes arrive.
Show worked solution
After the first read emit red and retain b"b". Append the second read to the retained suffix, emit blue at the newline, and retain an empty buffer. Handle end-of-stream with a nonempty suffix according to the protocol rather than silently inventing a complete record.
Check your solution
- The first read emits red and retains b"b".
- The second read emits blue and leaves no buffered bytes.
5. A user may export report A but not report B. A combined export is all-or-nothing: design a pre-stream authorization test for both reports.
Show hint
Authorize the complete requested set before starting a successful response.
Show worked solution
Request an export containing A and B and assert the documented denial, with neither report’s protected bytes emitted and no source opened under the stated fixture. As a control, request A alone and assert the allowed stream begins. This prevents a partial leak before B is checked.
Check your solution
- The mixed request is denied without opening the source or emitting protected bytes.
- The authorized A-only request begins successfully.
6. A stream sends HTTP 200 and one record, then its source fails before the final marker. Describe what the client and server can reliably observe.
Show hint
Headers already sent and application-level completion are separate facts.
Show worked solution
The client may observe 200 and a partial body, so it must mark the export incomplete when the required final marker is absent. The server should attempt source cleanup and record a safe failure category; it cannot rely on replacing already-sent headers with a new 500 response.
Check your solution
- The missing marker prevents the client declaring success.
- The source cleanup is attempted and the failure is safely recorded.
7. A protocol ends with {"complete":true,"count":3}. The client parsed only two complete data records. Is the marker sufficient?
Show hint
Validate marker count against parsed records.
Show worked solution
Reject the export as incomplete or invalid under this protocol: the declared count 3 disagrees with the two parsed data records. Test a matching count of 2 as a success control, and do not include the marker itself in the data count.
Check your solution
- A marker count of 3 with two data records is rejected.
- A marker count of 2 with those two records is accepted.
8. A line-framed export ends after b"{\"id\":2" with no newline or completion marker. What should an incremental client do with that suffix?
Show hint
A partial record and a missing completion marker are separate problems.
Show worked solution
Retain the unfinished suffix only while more bytes can arrive; on end-of-stream discard or report it as an incomplete record under the protocol. Mark the overall export incomplete because the required final marker is missing, and do not apply an effect from the partial record.
Check your solution
- The partial record is not applied as a complete record.
- The export is marked incomplete when the marker is absent.
9. A stream opens two synthetic files in sequence. The second open fails after the first file was fully consumed. Specify expected resource states.
Show hint
Each acquired file needs a cleanup boundary.
Show worked solution
Place each file acquisition inside its own generator-managed context. After file one finishes, assert it is closed before opening file two; if the second open fails, assert no second handle remains open and the stream reports failure under its protocol. Do not claim cleanup for a handle never acquired.
Check your solution
- The first file closes before the second open attempt.
- The failed second open leaves no acquired second handle.
10. A route returns a generator from inside a file context, but the generator opens the file only when iteration begins. Does the outer context protect its lifetime?
Show hint
Locate the actual acquisition, not merely generator creation.
Show worked solution
The outer context does not own the later-opened file. Open and close that file inside the generator’s own context, then use a controlled source to assert it remains open while records are read and closes on normal completion or proper generator closure. Generator construction alone does not start its body.
Check your solution
- The file remains open during actual iteration.
- The generator-owned handle closes when its lifecycle ends.
11. A cursor yields one row, then raises, and its close operation also raises. What should a test and error policy distinguish?
Show hint
The source failure and cleanup failure are different observations.
Show worked solution
Use a fake cursor to trigger both failures and record that close was attempted. Define how the application preserves or safely reports the original source error alongside the cleanup error without leaking row data; assert both categories are observable and the client does not accept an incomplete stream as complete.
Check your solution
- The cursor close attempt is recorded after the source failure.
- Both failures are safely observable and the incomplete stream is not accepted.
12. A controlled network test disconnects after one record while a producer waits on a gate. Design a bounded test of cancellation and resource cleanup.
Show hint
Control the producer state before closing the client connection.
Show worked solution
Start an isolated server and gated source; read the first framed record and wait until the producer reports it is blocked at the gate. Close the client connection, then observe cancellation or closure as supported by the tested stack and assert resource cleanup within a finite timeout. Release the gate in teardown to avoid a stuck test.
Check your solution
- The disconnect occurs after the first record and while the source is gated.
- Cleanup is observed within the bound and teardown releases the gate.
13. An in-process test confirms a complete stream, while a separate network test closes early through a buffering proxy. What distinct evidence should each record?
Show hint
Full-body correctness and disconnect propagation are different observations.
Show worked solution
Assert the in-process response has the expected complete representation and final marker. In the network test record when the proxy and upstream observe closure and whether the source closes within the chosen bound; report a timeout or buffering limitation rather than inferring cleanup from the first test.
Check your solution
- The in-process test validates the completed body and marker.
- The network test separately observes or reports limits on upstream cleanup.
14. A producer adds 40 chunks per second and a consumer removes 25; assume an initially empty unbounded queue and constant rates for 8 seconds. Calculate backlog.
Show hint
The queue grows by arrivals minus departures.
Show worked solution
The net arrival rate is 15 chunks per second, so after 8 seconds the backlog is 120 chunks under the stated idealized rates. Actual memory depends on chunk sizes and overhead; this count alone is not a byte measurement.
Check your solution
- The net backlog grows by 15 chunks per second.
- The idealized backlog after 8 seconds is 120 chunks.
15. A five-slot queue is full when the consumer disconnects and the producer is waiting to enqueue. Define a shutdown policy that cannot leave the producer waiting indefinitely.
Show hint
Coordinate producer cancellation or a bounded enqueue wait with resource closure.
Show worked solution
On detected disconnect signal the producer to stop, or use a bounded enqueue wait with a documented timeout and cancellation path. Ensure the producer exits and closes its owned source, and assert the queue never exceeds five slots. Test teardown even if the consumer stops draining.
Check your solution
- The producer exits within the specified bound after disconnect.
- The source closes and queue occupancy never exceeds five.
16. A pool has six connections and policy reserves two for ordinary queries. How many cursor streams may be admitted, assuming one connection each and no other users?
Show hint
Subtract the explicit reservation from pool capacity.
Show worked solution
At most four simultaneous cursor streams may be admitted under these assumptions, leaving two connections for ordinary queries. Test admission of the fourth stream and rejection or waiting of a fifth according to policy; monitor actual pool use because other consumers change available capacity.
Check your solution
- Four streams leave two reserved connections.
- A fifth stream is not admitted while the four slots are occupied.
17. Two workers allow three streams each, but a shared gateway enforces a global limit of four. If both workers have two streams, what happens to a fifth request under a reject-on-full policy?
Show hint
The shared limit and local limits must both permit admission.
Show worked solution
The four existing streams exhaust the gateway limit even though each worker has one local slot left. Reject the fifth request according to the documented policy; after one stream ends and its shared permit is released, a new request may be admitted if its worker has capacity.
Check your solution
- The fifth concurrent request is rejected at the shared limit.
- Releasing one permit allows a later eligible request.
18. A consumer applies record 2 but crashes before saving its checkpoint; the retry includes record 2 again. How can it prevent a duplicate effect?
Show hint
The effect and deduplication marker need a shared durable boundary.
Show worked solution
Use stable record IDs and atomically persist the effect and processed-ID marker when both live in the same transactional store. On retry skip record 2 if its marker committed; otherwise apply and mark it together. For external effects use the destination’s documented idempotency protocol.
Check your solution
- A committed marker prevents a second effect for record 2.
- An uncommitted effect and marker can be retried together.
19. A cancelled stream has a synchronous read blocked in a worker thread. The source documents a finite read timeout but does not support concurrent close. Design cleanup ordering.
Show hint
Do not close a source concurrently unless its library permits it.
Show worked solution
Stop scheduling new reads, let the outstanding read return or time out, then close the source according to its documented thread-safety rules. In a controlled test cancel while the read is blocked and assert no new read begins and cleanup occurs after the outstanding operation ends within its configured bound.
Check your solution
- Cancellation prevents new reads from being scheduled.
- The source closes after the outstanding read returns or times out.
20. A stream logs a source exception whose message contains a synthetic record and token. Design a diagnostic test that preserves correlation without leaking either value.
Show hint
Check the actual captured log, including exception messages.
Show worked solution
Trigger the synthetic failure with unique record and token markers. Assert the captured diagnostic includes an approved failure category and request ID, but neither marker in fields or formatted exception text. Apply the same redaction expectation to the public error path where applicable.
Check your solution
- The diagnostic includes the safe event and request ID.
- Neither synthetic marker appears in captured log output.
Key takeaways
- Streaming changes response timing and failure handling, not authorization duties.
- Resource ownership and disconnect behavior require integration evidence.
- Once a response has started, a later failure cannot reliably replace its status.
- A streaming source must remain valid during consumption and be cleaned up.
- In-process clients do not prove network disconnect or proxy behavior.