MVP Factory
EN
ai startup development

Kotlin coroutines channels and backpressure: building a resilient event bus

KW
Krystian Wiewiór · · 4 min read

Meta description: Deep dive into Kotlin Coroutines Channel capacity modes, fan-out dispatch with SharedFlow, slow consumer isolation using supervisorScope, and the buffer math that prevents OOM or stalls.

Tags: kotlin android architecture mobile jetpackcompose


TL;DR

Kotlin Coroutines Channels give you four capacity modes with fundamentally different backpressure semantics. Building a production-grade event bus means choosing the right mode, isolating slow consumers with supervisorScope, and doing explicit buffer math before you deploy — not after you OOM in production.


The problem most teams don’t see coming

Most teams treat event buses as fire-and-forget pub/sub, bolt on SharedFlow or BroadcastChannel, and ship. That works fine in development with two subscribers and a 60fps UI. Then production hits — a background analytics subscriber starts doing disk I/O on the same coroutine scope, and suddenly your entire pipeline stalls waiting for it to drain.

Backpressure isn’t a Rx-only concern. It lives in every concurrent system. Here’s the architecture that actually holds up.


Channel capacity modes: the foundation

Kotlin Coroutines offer four Channel capacity constants:

ModeBufferOn FullUse Case
RENDEZVOUS (0)NoneSuspends senderSynchronous handoff, tight coupling
BUFFERED (64 default)64 elementsSuspends senderGeneral purpose, bounded throughput
UNLIMITEDUnboundedNever suspendsBurst absorption — OOM risk
CONFLATED1 elementDrops old valueUI state, latest-value-wins

RENDEZVOUS is the strictest contract — your producer suspends until a consumer is ready. This eliminates buffering entirely and forces you to reason about throughput at the call site. BUFFERED is the pragmatic default for most event bus scenarios.

UNLIMITED is a footgun. An UNLIMITED channel connected to a slow consumer under sustained load will grow your heap until the OOM killer visits — I’ve seen it happen, and it’s not a fun postmortem. CONFLATED is purpose-built for UI state where intermediate values are irrelevant.


Fan-out dispatch: BroadcastChannel vs SharedFlow

BroadcastChannel is deprecated. Use SharedFlow.

val eventBus = MutableSharedFlow<AppEvent>(
    replay = 0,
    extraBufferCapacity = 64,
    onBufferOverflow = BufferOverflow.SUSPEND
)

SharedFlow fan-out dispatches to all active collectors concurrently. The critical parameter is onBufferOverflow:

  • SUSPEND — applies backpressure to the emitter
  • DROP_OLDEST — lossy, keeps pipeline moving
  • DROP_LATEST — lossy, protects existing buffer

For a typed event bus, SUSPEND is the correct default. Dropping events silently is a data integrity issue dressed up as a performance optimization.


Slow consumer isolation with supervisorScope

The architectural mistake that stalls pipelines: all consumers share the same coroutine scope. One blocking subscriber propagates backpressure to every other subscriber through the shared SharedFlow buffer.

Fix it with supervisorScope and per-consumer channels:

fun <T : AppEvent> subscribe(
    scope: CoroutineScope,
    eventClass: KClass<T>,
    capacity: Int = 32,
    block: suspend (T) -> Unit
) {
    val localChannel = Channel<T>(capacity = capacity, onUndeliveredElement = { /* log drop */ })

    scope.launch {
        eventBus
            .filterIsInstance(eventClass.java)
            .collect { event -> localChannel.trySend(event) }
    }

    scope.launch {
        supervisorScope {
            for (event in localChannel) {
                launch { block(event) }
            }
        }
    }
}

Each subscriber gets its own buffered Channel. trySend returns a ChannelResult — if the local channel is full, you drop for that subscriber only. The emitter never suspends. The pipeline never stalls. One lagging analytics subscriber cannot block your UI event stream.


The buffer math that matters

Run this before you ship:

Peak emission rate (events/sec) × Max consumer processing time (sec) = Required buffer depth

If your UI emits 120 scroll events/second and your analytics subscriber takes 50ms per event, you need 120 × 0.05 = 6 buffer slots minimum. Double it for burst headroom: capacity = 12. At 100 bytes per event, that’s 1.2KB — negligible. At UNLIMITED, a 10-second stall accumulates 1,200 events and 120KB. Scale that to complex domain objects and the math stops being comfortable.


Conclusion

A production Kotlin event bus isn’t a one-liner MutableSharedFlow. It’s a deliberate set of choices: which capacity mode, which overflow policy, how to keep consumers isolated from each other.

The things worth taking away:

  1. Default to BUFFERED with SUSPEND, then profile. Only switch to DROP_OLDEST after you’ve measured and explicitly accepted the data loss contract.
  2. Give every subscriber its own Channel with trySend. Never let a slow consumer’s backpressure propagate to unrelated subscribers through a shared flow.
  3. Do the buffer math before deployment. Peak emission rate × max processing time = minimum capacity. Ship with 2× that value and log every trySend failure in production.

Share: Twitter LinkedIn