Articles / Go

  • go
  • select
  • channels
  • concurrency
  • backpressure
  • debugging

Why a Go Select With a Default Case Quietly Drops Your Messages

You add a default case to a select so a send never blocks the producer. It works. Nothing hangs, nothing deadlocks. Then someone notices that only a handful of the thousand events you sent ever arrived, and nothing logged a single error.

That is the whole trade: a default case turns "wait" into "give up", and giving up looks exactly like success from the caller's side.

Reproducing it in thirty lines

Here is a producer that fires 1000 values at a slow consumer using a non-blocking send.

package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan int)
	done := make(chan struct{})

	received := 0
	go func() {
		defer close(done)
		for range ch {
			received++
			time.Sleep(time.Millisecond) // pretend to do work
		}
	}()

	dropped := 0
	for i := 0; i < 1000; i++ {
		select {
		case ch <- i:
		default:
			dropped++
		}
	}
	close(ch)
	<-done

	fmt.Println("received:", received, "dropped:", dropped)
}

The exact numbers vary between runs, but expect the consumer to see a tiny fraction and the dropped count to make up almost all of the rest. The producer finishes its loop far faster than the consumer finishes one sleep.

Why an unbuffered send fails so often

A send on an unbuffered channel only succeeds if a receiver is already parked on the other end at that instant. While the consumer is inside time.Sleep, nobody is receiving, so the send case is not ready and select picks default.

The spec says select runs default if no other case is ready. "Ready" is evaluated once, right now. There is no queue, no retry and no "I'll try again in a moment".

Quick detour: a buffer only moves the cliff

Giving the channel a buffer feels like a fix. make(chan int, 64) absorbs bursts nicely, and the drops disappear in your tests.

But the rule is the same: the send is ready while there is space, and not ready once the buffer is full. If the average producer rate exceeds the consumer rate for long enough, you get the same silent loss, just later and only under load. That is the worst time to find out.

Receiving with default is a different animal

A select with default on a receive is usually fine. It asks "is there anything to read right now?", and a no answer loses nothing, because the data stays in the channel.

The danger is specific to sends. On a send, the value only exists in the producer's hands, and default is the branch where it gets thrown away.

Three honest fixes

Decide what should happen when the consumer cannot keep up, then write that down in code. There are really only three answers.

  • Make the producer wait (backpressure), with a way out if it is cancelled.
  • Drop deliberately, and count what you dropped.
  • Keep only the newest value, because older ones are stale anyway.

1. Block, but stay cancellable

If every message matters, remove default and let the send block. Add the context so a stuck consumer cannot hold the producer forever.

func send(ctx context.Context, ch chan<- int, v int) error {
	select {
	case ch <- v:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

The caller now gets an error when the send did not happen, which the default version never gave you.

2. Drop on purpose, and make it visible

Sometimes dropping is right: metrics, debug events, a UI that can miss a frame. Keep the default, but count it.

type Sink struct {
	ch      chan int
	dropped atomic.Uint64
}

func (s *Sink) Offer(v int) bool {
	select {
	case s.ch <- v:
		return true
	default:
		s.dropped.Add(1)
		return false
	}
}

Returning a bool and exporting the counter means a rising drop rate shows up on a dashboard instead of in a bug report. Name the method Offer or TrySend, not Send, so readers know it can refuse.

3. Keep only the latest value

For state that supersedes itself (the current temperature, the newest config), a channel with capacity 1 and a "replace" send is neater than a queue.

func sendLatest(ch chan int, v int) {
	for {
		select {
		case ch <- v:
			return
		default:
		}
		select {
		case <-ch: // discard the stale value
		default:
		}
	}
}

If the buffer is full, the second select evicts the old value and the loop tries again. The loop matters: with several producers, another one may refill the slot between your eviction and your retry.

A quick way to find these in a codebase

Search for default: inside any select that has a send case. For each hit, ask what the caller believes happened. If the answer is "it was delivered" and the code cannot tell, that is the bug.

The same shape appears in handlers that push onto a work queue and still return 200 OK. The client sees success, and the job quietly never ran. Worth a grep.