DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.

← Back to Questions
MediumTheory

Explain Channel Behavior: Nil, Closed, and Blocking

9 views

Problem Statement

During a Google SRE interview, you're asked to explain the nuanced behavior of Go channels. A production outage was caused by a goroutine leak due to improper channel handling. Walk through all channel edge cases.

Channel Behavior Matrix

OperationNil ChannelClosed ChannelOpen Channel
ch <- valueBlocks foreverPANICSends or blocks
<-chBlocks foreverReturns zero value + falseReceives or blocks
close(ch)PANICPANICCloses successfully

The Goroutine Leak Scenario

package main

import (
    "fmt"
    "runtime"
    "time"
)

func leakyFunction() {
    ch := make(chan int)
    
    go func() {
        // This goroutine will block forever
        // because no one ever sends to ch
        val := <-ch
        fmt.Println("Received:", val)
    }()
    
    // Function returns, but goroutine is stuck
}

func main() {
    for i := 0; i < 1000; i++ {
        leakyFunction()
    }
    
    time.Sleep(time.Second)
    fmt.Printf("Goroutines: %d\n", runtime.NumGoroutine())
    // Output: Goroutines: 1001 (leaked!)
}

The Fix: Context-Based Cancellation

func properFunction(ctx context.Context) {
    ch := make(chan int)
    
    go func() {
        select {
        case val := <-ch:
            fmt.Println("Received:", val)
        case <-ctx.Done():
            fmt.Println("Cancelled, exiting goroutine")
            return
        }
    }()
}

Interview Questions

  1. Q: What happens if you read from a nil channel?
    A: It blocks forever. This is actually useful in select statements to disable a case.
  2. Q: Why would you intentionally use a nil channel?
    A: To dynamically disable a select case without removing the code.
  3. Q: How do you detect a closed channel?
    A: Use the two-value receive: val, ok := <-ch. If ok is false, channel is closed.

Real-World Production Issue

At Twitch, a service leaked 50,000 goroutines because websocket handlers were waiting on a channel that was never closed when clients disconnected. The fix: Always use context cancellation for cleanup.

No test cases available

Test cases will be added for this question soon.

No solutions yet

Be the first to share a solution for this question.

Comments (0)

Sign in to leave a comment.

No comments yet. Be the first to comment.

Stats

Views
9
Likes
0
Solutions
0
Comments
0

Category

Backend Engineering