# panic: runtime error: too many open files (in goroutine)

- **ID:** `go/too-many-open-files-in-goroutine`
- **Domain:** go
- **Category:** io_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

A goroutine is opening many file descriptors without closing them, exhausting the system limit. This can happen in concurrent programs that handle many connections or files.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 1.0 | active | — | — |
| 1.1 | active | — | — |
| 1.2 | active | — | — |

## Workarounds

1. **Use a semaphore to limit concurrent file operations** (90% success)
   ```
   sem := make(chan struct{}, 10) // limit 10 concurrent opens
for i := 0; i < 100; i++ {
    go func() {
        sem <- struct{}{}
        defer func() { <-sem }()
        f, err := os.Open("file.txt")
        if err != nil {
            log.Fatal(err)
        }
        defer f.Close()
        // process file
    }()
}
   ```
2. **Ensure all files are closed in a timely manner** (95% success)
   ```
   f, err := os.Open("file.txt")
if err != nil {
    return err
}
defer f.Close()
// use f
   ```

## Dead Ends

- **Increasing the system ulimit without fixing the code** — This only delays the problem; if the code doesn't close files properly, the new limit will also be exhausted eventually. (80% fail)
- **Using defer to close files but not handling errors** — defer ensures close is called, but if multiple goroutines open files concurrently, the defer may not execute quickly enough, leading to file descriptor exhaustion. (70% fail)
