Course outline

Kotlin / Concurrency, interoperability, and integrated design / Lesson 21

Bounded channels and completion

Coordinate bounded Kotlin coroutine channels and cancellation.

About 22 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Choose a bounded channel policy.
  • Test closure and cancellation.
  • Trace bounded channel acceptance, processing and closure as distinct events.
  • Design owned cancellation and element cleanup for early-exit paths.

Define the channel contract

A bounded coroutine channel connects producers and consumers while limiting queued elements. Its capacity and overflow policy determine whether sending suspends or an element is dropped. Define who owns channel closure, how failures and cancellation propagate, and whether every submitted item must be processed. A capacity limit bounds queued elements, not necessarily all memory held by tasks or elements.

Observe a full buffer

With a capacity-one channel and the default suspending overflow policy, trySend succeeds for the first element and reports failure immediately for the second while the buffer is full. The first example demonstrates that result without depending on scheduling. A successful send means the channel accepted an element; it does not mean a consumer has already processed it. Select a dropping policy only when loss is acceptable.

kotlin A bounded coroutine channel
import kotlinx.coroutines.channels.Channel

fun main() {
    val channel = Channel<Int>(1)
    println("${channel.trySend(1).isSuccess} ${channel.trySend(2).isSuccess}")
    channel.close()
}
Expected output
true false

The second non-suspending send finds the buffer full.

Close and drain

Closing the channel signals that no more elements will be sent. A receiver can consume buffered elements and finish iteration after closure. The second example sends one value, closes the channel, and drains it. With several producers, coordinate closure only after all have finished; an individual producer must not close the channel while another can still send.

kotlin A bounded coroutine channel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val channel = Channel<Int>(1)
    channel.send(7)
    channel.close()
    for (value in channel) println(value)
}
Expected output
7

The buffered value is received before iteration ends.

Coordinate cancellation

A suspended sender needs a cancellation or completion path when a consumer exits early. Keep producer and consumer coroutines within an owned scope and propagate cancellation without swallowing it. Release owned resources in finally blocks as appropriate. Closing a channel and cancelling a coroutine are distinct operations; define how errors and already accepted elements are handled in each case.

Test backpressure

Test a full channel, closure with buffered data, early consumer exit, and cancellation of a pending send. Use controlled coroutine scheduling and await owned work instead of asserting exact timing. Verify whether each submitted element is processed, rejected, or deliberately dropped according to the selected policy. A test that receives immediately cannot establish backpressure behavior.

Specify capacity and full behavior

A channel transfers elements between coroutines; its capacity and overflow policy describe the queue boundary, not the entire application’s memory use. With a capacity-one Channel and the default suspending overflow policy, one element can be buffered when there is no receiver. A second send may suspend until progress is possible, while trySend returns immediately with a result that the caller must inspect. A failed non-suspending attempt can mean a full channel or a closed channel; use the result and documented API to distinguish them rather than treating every failure as backpressure.

A rendezvous channel has no buffer: a successful transfer requires a corresponding sender and receiver to meet. A positive-capacity buffer can absorb a bounded number of waiting elements, but active workers and the objects they hold consume additional resources. Dropping overflow policies change delivery semantics and can report successful send operations even when an element is discarded under that policy. Decide whether every command must be accounted for before choosing a policy. Compatible kotlinx.coroutines is a separate dependency; all examples here are unexecuted Kotlin/JVM illustrations or synthetic traces.

Separate acceptance from processing

A successful send or trySend reports the channel operation’s outcome, not completion of the business work. An element may still be buffered or being processed, and a consumer can fail afterward. If the producer must know that processing finished, design a separate acknowledgment or result channel with an owner and failure policy. For a durable command, persist the accepted intent and define identity, retries and recovery at an appropriate authoritative boundary; an in-memory channel is not a durable queue.

Trace each element through submitted, accepted, received and processed states. For a buffer of two containing A and B, a third immediate trySend with a suspending overflow policy fails while the buffer remains full. After one receive frees space, a new attempt may succeed if the channel is still open. Test the actual result of every operation, and do not assume a failed trySend transferred ownership of its element. For resource-bearing elements, specify who closes them on send failure, cancellation, or undelivered delivery according to the selected library API.

Coordinate closure and cancellation

Normal close signals that no new sends should be initiated through the channel; buffered elements can be received before iteration completes. With multiple producers, a coordinator that knows all producers have completed can close after their work, rather than letting the first producer close while others still need to send. Close and coroutine cancellation are different actions. A failure close carries a cause to receivers according to the API, while channel cancellation has its own semantics for pending and buffered elements; consult the exact library version and ownership hooks.

Do not assume close simply cancels every already suspended send. The documented channel behavior distinguishes sends that were already suspended before close from sends initiated after closure. A consumer that stops early needs an explicit policy for the producer and any accepted elements; merely waiting for a sender blocked by a full buffer can hang. Cancel or otherwise coordinate the owned jobs and channel as appropriate, and wait for cleanup. A cancellation request still does not prove that an external action performed by a consumer was rolled back.

In the normal-completion walkthrough, the single producer owns closure in finally, and the consumer drains the channel before both jobs are joined. The fixed values establish an expected order, not a timing measurement. For multiple producers the owner must coordinate all of them before normal closure; an early consumer exit needs a separate cancellation policy.

kotlin Single producer, bounded channel and owned drain
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.Channel

fun main() = runBlocking {
    val channel = Channel<Int>(capacity = 1)
    val received = mutableListOf<Int>()
    val producer = launch {
        try {
            channel.send(2)
            channel.send(3)
        } finally {
            channel.close()
        }
    }
    val consumer = launch {
        for (value in channel) received.add(value)
    }
    joinAll(producer, consumer)
    println(received.joinToString(","))
}
Expected output
2,3

Expected output is 2,3 on the normal completion path. The program requires compatible kotlinx.coroutines and was not executed; it does not establish durable processing.

Make element and scope ownership explicit

An element may itself own a resource. Define when ownership transfers from producer to channel to consumer, and how a resource is released if transfer fails or a queued element is undelivered. kotlinx.coroutines provides an onUndeliveredElement mechanism for cases described by the Channel API, but its exact invocation and exception behavior must be understood for the selected version. A failed trySend has its own documented ownership consequences; do not assume a callback disposes every element that was never accepted. Keep cleanup small, safe and testable.

Keep producers and consumers in a scope whose owner can observe failure and cancellation. If a consumer stops after one element, the owner must decide whether remaining elements are drained, deliberately discarded, persisted elsewhere, or cause the operation to fail. For an external side effect, a receiver may fail after the side effect but before acknowledgment. Use stable operation identities and the real service’s idempotency or reconciliation contract rather than equating channel receipt with a completed transaction. Document whether ordering applies to acceptance, processing start, or completed effects.

Test full, close and early-exit paths

Use controlled gates to establish that a buffer is full or a sender is suspended before triggering a receive, close or cancellation. A test that immediately receives every value may never exercise backpressure. Cover successful and failed trySend, normal close with buffered data, a failure cause, multiple producer completion and early consumer exit. Count submitted, accepted, received, processed and deliberately discarded items separately; an accepted count alone is not evidence of successful processing.

For resource-bearing elements, force failure before acceptance and cancellation after acceptance, and assert the documented owner or undelivered cleanup path exactly once under the chosen fixture. Test concurrent external effects and durability at their actual storage boundary in an authorized isolated environment; a fake channel test does not prove production persistence or timing. The complete walkthrough below uses a compatible Kotlin/JVM and kotlinx.coroutines setup and remains unexecuted. Record actual library versions, scheduler and observed results before claiming a pass; structural validation does not run channels.

20 worked examples

1. First buffered send

Problem: What does the first immediate attempt report?

  1. The channel is open and its single buffer slot is free.
  2. The element is accepted into that slot.
text Controlled synthetic channel trace
Channel<Int>(capacity=1); buffer empty
trySend(1); no receiver

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: success; buffer contains 1

Why this result follows: Acceptance is a channel operation result, not a processing acknowledgment.

2. Full immediate attempt

Problem: What does the second trySend report?

  1. The first element occupies the only buffer slot.
  2. With no receiver or space, the non-suspending second attempt fails.
text Controlled synthetic channel trace
Channel<Int>(capacity=1, overflow=SUSPEND)
trySend(1) succeeds; no receive
trySend(2)

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: failure; buffer still contains 1

Why this result follows: trySend reports lack of immediate capacity without suspending.

3. Receive frees space

Problem: What can the new immediate attempt do?

  1. Receiving 1 frees the single buffer slot.
  2. The open channel can accept 2 into that slot.
text Controlled synthetic channel trace
capacity=1; buffer contains 1
receiver receives 1
trySend(2) while channel remains open

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: success; buffer contains 2

Why this result follows: A later attempt can succeed after capacity becomes available.

4. Suspending send

Problem: What happens while the buffer remains full?

  1. The configured policy does not drop an element to make room.
  2. send(B) can suspend until it can progress or is canceled.
text Controlled synthetic channel trace
capacity=1; overflow=SUSPEND; buffer contains A
producer calls send(B)
no receiver yet

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: sender pending under stated conditions

Why this result follows: A bounded queue can apply backpressure to a cooperative sender.

5. Rendezvous without receiver

Problem: Can the channel buffer A while no receiver exists?

  1. A rendezvous channel has no buffer slot.
  2. The suspending send waits for a matching receiver or cancellation.
text Controlled synthetic channel trace
Channel.RENDEZVOUS
producer attempts send(A)
no receiver is ready

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: sender pending; no buffered element

Why this result follows: Rendezvous transfers require sender and receiver coordination.

6. Normal close and drain

Problem: What happens to the buffered value before iteration ends?

  1. The value 7 was accepted before normal closure.
  2. A receiver can consume the buffered value and then observe completion.
text Controlled synthetic channel trace
capacity=1
send(7) completes
close normally
receiver drains channel

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: 7 received; iteration ends

Why this result follows: Normal closure allows buffered values to drain.

7. Send after closure

Problem: What does a new non-suspending send attempt report?

  1. The channel has already been closed.
  2. trySend does not accept the newly attempted element and reports failure.
text Controlled synthetic channel trace
channel closed normally
new producer calls trySend(2)

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: failure with closed channel

Why this result follows: New sends cannot use a channel after its closure.

8. Close with cause

Problem: What must the receiver’s contract account for?

  1. The channel is closed with a failure cause rather than normal completion.
  2. After buffered elements are handled, the receiver observes closure according to the API and cause.
text Controlled synthetic channel trace
channel closed with synthetic cause E
buffer drained
receiver observes closure

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: failure cause E is not normal completion

Why this result follows: A close cause is part of the failure boundary.

9. Inspect closed receive

Problem: How can the caller distinguish closure from an element?

  1. receiveCatching returns a result representing success or closure.
  2. With an empty normally closed channel, the result reports closed rather than an element.
text Controlled synthetic channel trace
channel closed normally and empty
val result = channel.receiveCatching()
inspect result

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: closed result; no element

Why this result follows: The caller must inspect the result instead of inventing a value.

10. Cancel differs from close

Problem: Why must the owner not assume normal draining here?

  1. Cancellation and normal close have different channel semantics.
  2. The selected cancellation policy can discard queued elements and invoke documented undelivered handling.
text Controlled synthetic channel trace
channel has buffered elements
owner cancels channel
normal drain is not requested

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: handle discarded elements under the chosen contract

Why this result follows: Cancellation is not interchangeable with a normal close-and-drain workflow.

11. Multiple producer ownership

Problem: Should A close the channel immediately after it finishes?

  1. B may still need to send elements.
  2. The coordinator closes only after both producers complete under this contract.
text Controlled synthetic channel trace
producers A and B send to one channel
A finishes
B remains active
coordinator waits for both

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: wait for B before normal close

Why this result follows: Closure ownership must cover all producers.

12. Accepted is not processed

Problem: Has the consumer processed A?

  1. The channel accepted A in the stated trace.
  2. No receive or processing completion has been observed.
text Controlled synthetic channel trace
producer trySend(A): success
consumer has not yet received A

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: processing not established

Why this result follows: Channel acceptance is not a business-effect acknowledgment.

13. Explicit acknowledgment

Problem: What extra event establishes local processing completion?

  1. Receiving A alone starts the consumer’s work.
  2. The acknowledgment is sent after the stated local processing completes.
text Controlled synthetic channel trace
consumer receives A
consumer completes local processing
consumer sends acknowledgment for A

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: A acknowledged after local processing

Why this result follows: The acknowledgment contract is separate from channel acceptance.

14. Drop oldest policy

Problem: What remains buffered in this controlled scenario?

  1. The buffer is full with A.
  2. The policy discards the oldest buffered element to retain the newer B.
text Controlled synthetic channel trace
capacity=1; policy=DROP_OLDEST
buffer contains A
send B while consumer is absent

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: B remains; A dropped

Why this result follows: A dropping policy changes which values are available to the consumer.

15. Drop latest policy

Problem: What remains buffered under this different policy?

  1. The buffer is full with A.
  2. The policy discards the newly offered B and retains A.
text Controlled synthetic channel trace
capacity=1; policy=DROP_LATEST
buffer contains A
send B while consumer is absent

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: A remains; B dropped

Why this result follows: Different overflow policies have different business consequences.

16. Canceled pending sender

Problem: What should the owner verify after cancellation?

  1. The sender was pending because the buffer was full.
  2. The owner waits for its cancellation path and checks any element ownership obligations.
text Controlled synthetic channel trace
capacity=1; buffer full
sender suspended in send(B)
owner cancels sender and joins it

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: sender completes; B handling follows documented policy

Why this result follows: A pending send needs a cancellation and ownership policy.

17. Early consumer exit

Problem: What risk exists if the owner only waits for the producer?

  1. No consumer remains to free channel capacity in the trace.
  2. The producer can remain suspended on a later send.
text Controlled synthetic channel trace
consumer receives first element then exits
producer attempts further send into full channel
no coordinator action

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: shutdown may hang

Why this result follows: Early exit requires coordinated cancellation or another completion policy.

18. Undelivered resource

Problem: What must the fixture verify?

  1. R requires cleanup even though no consumer processed it.
  2. The configured owner or hook must perform the documented release path.
text Controlled synthetic channel trace
element R owns a synthetic resource
accepted into channel
channel cancellation leaves R undelivered
fixture has documented cleanup hook

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: R cleanup recorded under fixture policy

Why this result follows: Element ownership continues through cancellation and undelivered paths.

19. Controlled backpressure test

Problem: What does this test establish under its fixture?

  1. The gate confirms B is waiting while the buffer is full.
  2. Receiving A frees capacity and lets the owned sender complete.
text Controlled synthetic channel trace
test: fill capacity-one channel
test: start sender B and confirm it is pending
test: receive A; join sender

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: B completes after capacity is freed

Why this result follows: Controlled ordering tests backpressure without relying on a sleep.

20. In-memory channel limit

Problem: Does acceptance prove command K survives restart?

  1. The trace provides only in-memory channel acceptance.
  2. No durable record or recovery contract is established.
text Controlled synthetic channel trace
channel accepts command K
process crashes before durable record
restart occurs

This trace assumes a compatible library, stated policy and event ordering; no channel was executed.

Expected result: durable delivery unverified

Why this result follows: Persistence and recovery require a separate authoritative design.

Common errors and fixes

A sender remains suspended

Why it happens
The consumer exited while the buffer was full.
How to fix it
Provide a coordinated cancellation path.
Prevent it next time
Test early consumer exit.

A send fails after closure

Why it happens
A producer closed the channel before others finished.
How to fix it
Coordinate closure after all producers complete.
Prevent it next time
Document closure ownership.

An accepted item is assumed processed

Why it happens
Sending was confused with consumer completion.
How to fix it
Track processing completion separately.
Prevent it next time
Test the full processing contract.

20 practice exercises

1. Why does the second trySend fail in the first example?

Show hint

Trace buffer occupancy before the second immediate attempt.

Show worked solution

The first value fills the capacity-one channel, so the non-suspending second attempt reports failure.

The first trySend places one element in the capacity-one buffer. With no receive and the default suspending overflow policy, there is no immediate space for the second element, so trySend reports failure rather than suspending. This does not establish that the first element was processed.

Check your solution

  • The first attempt succeeds and fills the slot.
  • The second immediate attempt fails while the slot remains full.

2. Who should close a channel with multiple producers?

Show hint

Identify the owner that can observe all producer completions.

Show worked solution

A coordinator that knows all producers are finished can close it without interrupting another producer.

A coordinator should wait for all producers under the selected failure and cancellation policy, then close normally when no producer needs to initiate another send. A single producer closing early can disrupt others; define how failure changes the close or cancel decision.

Check your solution

  • Normal closure follows all producer completions.
  • Producer failure has an explicit coordination policy.

3. An open capacity-two channel with SUSPEND policy receives successful trySend(A) and trySend(B); trySend(C) then fails. A consumer receives A but has not processed it. Report buffered, accepted and processed counts.

Show hint

Track acceptance separately from processing.

Show worked solution

A and B were accepted; C was not. After receiving A, B remains buffered, and no completed processing is stated, so accepted=2, buffered=1 and processed is not established. Retry C only under the caller’s documented policy.

Check your solution

  • The buffer contains B after A is received.
  • Acceptance of two items is not reported as two completed effects.

4. A trySend fails once because an open channel is full and once because it is closed. Design distinct caller actions and tests.

Show hint

Inspect the ChannelResult rather than assuming one cause.

Show worked solution

For a full open channel under the selected policy, the caller can retry or back off according to its contract. For a closed result, follow the terminal failure or shutdown policy rather than retrying indefinitely; test both with controlled fixtures.

Check your solution

  • The full and closed failures are distinguished.
  • The closed case does not enter an unbounded retry loop.

5. A capacity-one channel contains A while senders B and C are both known to be pending. Cancel and join B before receiving A; design a controlled test of C and element ownership.

Show hint

Coordinate both pending sends before canceling only B.

Show worked solution

Use gates or a suitable test scheduler to establish both sends are pending, cancel and join B before freeing the slot, then receive A and wait for C to complete. Assert C can be received, B did not complete its send in this fixture, and B’s element follows the selected API ownership and cleanup contract.

Check your solution

  • B is canceled and joined before the slot is freed.
  • C completes after A is received and B’s element is accounted for.

6. A receiver drains a channel normally closed in one test and a channel closed with cause E in another. Design separate observations.

Show hint

Normal completion and failure closure are different contracts.

Show worked solution

In both fixtures first account for any accepted buffered items. Then assert normal completion for the first and observation of cause E according to the chosen receive API for the second; do not treat both as the same empty success.

Check your solution

  • Buffered values are accounted for.
  • The failure cause is distinguished from normal closure.

7. Three producers share a channel; one fails before the others finish. Design a coordinator policy for closure and remaining work.

Show hint

The coordinator owns more than the first producer’s completion.

Show worked solution

Specify whether the shared task fails together or remaining producers may finish, observe the failing producer, and close or cancel according to that policy only after coordinating all jobs. Test a forced failure with the other two known to be active.

Check your solution

  • No producer closes the channel prematurely under the chosen policy.
  • The failure and all producer completions are observed.

8. A channel accepted command K; the consumer fails after receiving it but before acknowledgment. Design a recovery contract.

Show hint

Acceptance and processing acknowledgment are separate.

Show worked solution

Record or recover K at an appropriate durable boundary, and define whether a retry is safe using an idempotency or reconciliation policy. A successful send alone cannot prove completion; test a controlled failure between receive and acknowledgment.

Check your solution

  • The unacknowledged command remains accounted for under the recovery contract.
  • A retry cannot silently duplicate an external effect.

9. A capacity-two channel contains A and B when C arrives. Compare DROP_OLDEST and DROP_LATEST outcomes and explain the business decision.

Show hint

Identify which element each policy discards.

Show worked solution

Under DROP_OLDEST the controlled buffer becomes B, C; under DROP_LATEST it remains A, B and C is discarded. Choose only if the domain permits that loss, and test accepted, dropped and processed counts rather than using send success as a delivery count.

Check your solution

  • DROP_OLDEST retains B and C.
  • DROP_LATEST retains A and B.

10. A resource-bearing element fails trySend because the channel is full. Who handles the element, and what should a test verify?

Show hint

A failed immediate send did not accept the element.

Show worked solution

Follow the selected Channel API’s documented ownership behavior: the caller must handle the unsuccessful element rather than assuming onUndeliveredElement cleaned it up. Use a fake resource and assert the caller’s release or retry path runs once without double cleanup.

Check your solution

  • The unsuccessful element has an explicit owner.
  • The test detects both a leak and double release.

11. A channel has capacity 10, but 100 launched workers each hold a large object before sending. Does capacity bound total memory? Propose an additional limit.

Show hint

Buffered elements are only one source of retained memory.

Show worked solution

The channel bounds queued elements according to its configuration, not all objects held by suspended senders or active workers. Bound the number of active producers or permits and measure representative memory under the actual workload.

Check your solution

  • The ten-slot bound is not claimed as a total-memory bound.
  • Active producers have a separate limit.

12. A rendezvous sender waits with no receiver, and the owner cancels the operation. Design a completion and cleanup test.

Show hint

No buffered slot allows the send to complete alone.

Show worked solution

Start the sender in an owned scope, coordinate that it has reached the pending send, then cancel and join it. Verify its finally cleanup and element ownership under the selected API; do not wait indefinitely for a receiver that will never start.

Check your solution

  • The pending sender is canceled and joined.
  • Cleanup and element ownership are checked.

13. A consumer stops after the first item while a producer may be suspended on a full channel. Define a complete shutdown policy.

Show hint

The owner must coordinate both jobs and accepted elements.

Show worked solution

Decide whether to drain or deliberately cancel and account for remaining elements, then signal the producer and wait for both jobs to finish. Test early exit with controlled gates and verify cleanup and each submitted item’s documented disposition.

Check your solution

  • No producer is left indefinitely suspended.
  • Accepted and undelivered elements have explicit outcomes.

14. A sender was already suspended before another coroutine closes the channel. Why is assuming close cancels that send unsafe, and what should be tested?

Show hint

The API distinguishes already-suspended and newly initiated sends.

Show worked solution

Consult the selected kotlinx.coroutines version’s close contract: an already suspended send is not simply canceled by close and may complete as receivers progress. Test the pending sender, a new post-close attempt, and the owner’s cancellation policy with controlled scheduling.

Check your solution

  • The pending send is not assumed canceled by close.
  • A new post-close attempt follows the documented closed result.

15. A channel has accepted buffered A and B. Compare normal close-and-drain with cancellation when the contract requires reporting any discarded resource.

Show hint

The two terminal actions have different element consequences.

Show worked solution

For normal close, drain the accepted buffer before the receiver finishes. For cancellation, follow the API’s documented undelivered-element behavior and record any discarded resource under the ownership policy; test the two paths independently.

Check your solution

  • The normal path receives the buffered values.
  • The cancellation path accounts for any undelivered resources.

16. A channel transfers closeable resources and cancellation can race with delivery. Design an ownership test without promising a particular schedule.

Show hint

Specify who owns each element at every outcome.

Show worked solution

Use synthetic resources with unique IDs and a cleanup counter, then coordinate accepted, received and canceled paths. Assert every resource is either handed to a consumer that closes it or handled by the documented undelivered/caller path exactly once; do not assume which race winner occurs.

Check your solution

  • Every synthetic resource has one accountable owner.
  • No fixture path leaks or double-closes a resource.

17. A queue has capacity 5 and a semaphore permits 2 active workers. Explain what each limit covers and what remains unbounded unless designed.

Show hint

Queue capacity and active processing concurrency are different quantities.

Show worked solution

The channel bounds buffered elements under its configuration, while the semaphore bounds active permit holders to two. Suspended producers, object sizes and external resource use may still need separate limits; test each bound independently.

Check your solution

  • The two limits are not conflated.
  • Additional retained memory or producers are considered.

18. A consumer performs a remote write for command K and crashes before acknowledging it. Design a retry policy that does not treat channel receipt as exactly-once processing.

Show hint

The external effect may already have happened.

Show worked solution

Record a stable command identity and follow the remote service’s documented idempotency or reconciliation policy before retrying. Simulate a committed write followed by lost acknowledgment in an isolated fake, then verify one logical effect under that contract.

Check your solution

  • The outcome after the crash is treated as uncertain until reconciled.
  • A retry uses the same identity under the stated policy.

19. Design a gated test for three submitted items with capacity one and a consumer that stops after one. What counts and outcomes must be recorded?

Show hint

Submitted, accepted and processed are not interchangeable.

Show worked solution

Coordinate the consumer’s first receipt and early exit, then cancel or drain according to the policy and join all owned jobs. Record which items were submitted, accepted, processed, rejected or undelivered, and verify cleanup for any resource-bearing item.

Check your solution

  • Every submitted item has a documented disposition.
  • No owned sender remains pending after shutdown.

20. A fake-channel test passes, but no real durable queue, external service or process-restart test ran. Write a scoped report.

Show hint

Separate local channel behavior from untested integration boundaries.

Show worked solution

Report the channel configuration, controlled ordering and assertions observed in the isolated test. Mark durability, external idempotency and restart recovery unverified until separately authorized integration tests provide evidence.

Check your solution

  • The fake fixture and observed checks are named.
  • Untested durability and recovery are explicitly unverified.

Key takeaways

  • A bounded channel needs explicit full and closure policies.
  • Coordinate cancellation and completion across the scope.
  • Capacity and overflow policy define queue behavior, not total application memory.
  • A successful send is not proof of completed processing.
  • Normal close, channel cancellation and job cancellation have distinct contracts.

Official references