Bound connection lifetime and backpressure
Bound connection lifetime and backpressure
Backpressure occurs when producers generate data faster than consumers can accept it. A socket write can block as buffers fill. Bound queue capacity, connection count, message sizes and I/O time. Decide explicitly whether full queues block, reject or drop work; never create unlimited goroutines to hide a slow peer. A connection owner must close it during shutdown.
package main
import ( "fmt")
func main() { queue := make(chan string, 2) for _, msg := range []string{"A", "B", "C"} { select { case queue <- msg: fmt.Println("queued", msg) default: fmt.Println("busy", msg) } } close(queue) for msg := range queue { fmt.Println("send", msg) }}This is an explicit reject-on-full policy: C is never silently queued. One writer can drain the bounded queue and serialize complete frames. This example models the application queue, not actual TCP buffer capacity. In a real system inform callers of rejection and select a policy suitable for data loss and retry semantics.
Expected output:
queued Aqueued Bbusy Csend Asend BUnblock a reader by closing its connection
package main
import ( "fmt" "net" "time")
func main() { a, b := net.Pipe() defer b.Close() ready := make(chan struct{}) done := make(chan error, 1) go func() { close(ready); _, e := a.Read(make([]byte, 1)); done <- e }() <-ready if e := a.Close(); e != nil { panic(e) } select { case e := <-done: fmt.Println(e != nil) case <-time.After(time.Second): panic("reader did not stop") }}Close makes pending I/O return an error and prevents new I/O. The ready signal means the goroutine has started, not necessarily that Read is blocked yet; Close works in either ordering. Wait for worker exit during shutdown. Closing a listener alone does not close accepted sockets. In a production server, stop accepting, cancel or drain bounded work, close remaining connections at the deadline, then wait for handlers.
Expected output:
trueTry it locally
Use a queue of capacity one; attempt to enqueue 10 then 20 without blocking. Print whether each attempt succeeds and the queued value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Networking 08: Bound connection lifetime and backpressure
Check the lesson objective before moving on.
What is a useful response to a full bounded queue?
How can a connection owner unblock pending reads during shutdown?