Stream Large Files and HTTP Bodies With bufio.Scanner and io.LimitReader
Read large text streams line by line with bufio.Scanner, copy streams in bounded memory with io.Copy, and cap untrusted HTTP bodies with io.LimitReader. After this, large payloads will not exhaust RAM.
Skip ahead
Already streaming with io.Copy? Jump to Case 2: bounding untrusted streams with io.LimitReader or Case 3: hashing while saving with io.TeeReader.
Calling os.ReadFile or io.ReadAll(r.Body) on a 1.5 GB CSV export or uploaded backup forces Go to allocate 1.5 GB of RAM before processing the first byte. Under just five concurrent uploads, an 8 GB container hits OOMKilled.
Go avoids buffering whole payloads in memory by streaming fixed 32 KB chunks across two tiny one-method interfaces: io.Reader and io.Writer. Verified on Go 1.27.
Case 1: Streaming with io.Copy vs. buffering with io.ReadAll
Files (*os.File), HTTP request bodies (r.Body), HTTP response writers (w), gzip streams, SHA-256 hashers, and bytes.Buffer all implement io.Reader or io.Writer. io.Copy(dst, src) reuses a single 32 KB buffer until io.EOF—so copying 50 MB or 50 GB uses the exact same ~32 KB of RAM:
// Bad for large payloads: allocates entire stream in RAM
body, err := io.ReadAll(r.Body)
// Good: streams 32 KB chunks straight to disk or another writer
n, err := io.Copy(dstFile, r.Body)
Case 2: Bounding untrusted streams with io.LimitReader
Even when streaming, a malicious or broken client can keep sending bytes forever to fill your disk. Wrapping any io.Reader in io.LimitReader(src, maxBytes) halts reading cleanly at maxBytes with zero extra buffer allocation:
package main
import (
"bytes"
"fmt"
"io"
"strings"
)
func main() {
src := strings.NewReader("header:payload-that-keeps-going")
var dst bytes.Buffer
n, err := io.Copy(&dst, io.LimitReader(src, 14))
fmt.Printf("copied=%d err=%v data=%q\n", n, err, dst.String())
}
copied=14 err=<nil> data="header:payload"
Notice that io.LimitReader returns io.EOF cleanly at byte 14, so io.Copy returns err == nil. Inside HTTP handlers where you want to reject oversized payloads with 413 Payload Too Large, wrap r.Body with http.MaxBytesReader(w, r.Body, maxBytes) instead—it returns a typed *http.MaxBytesError and closes the connection cleanly.
Case 3: Computing a SHA-256 checksum while saving with io.TeeReader
Suppose your upload handler must save an incoming file to disk and record its SHA-256 digest. Instead of saving the file and then reading all 2 GB back off disk a second time, snap io.TeeReader(src, hasher) into the pipeline so every byte copied to disk is hashed on the exact same pass:
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"strings"
)
func main() {
src := strings.NewReader("invoice,1200\nshipping,150\n")
h := sha256.New()
var disk bytes.Buffer
n, err := io.Copy(&disk, io.TeeReader(src, h))
fmt.Printf("bytes=%d err=%v sha256=%x\n", n, err, h.Sum(nil)[:8])
}
bytes=26 err=<nil> sha256=330bb2a2ea1bbbb3
Case 4: Line-by-line streaming and the 64 KB bufio.Scanner limit
For large log or NDJSON files, bufio.NewScanner(r) streams one line at a time—just remember two mandatory rules: always check if err := scanner.Err(); err != nil after the loop, and raise its 64 KB default token cap with scanner.Buffer(make([]byte, 64*1024), 1024*1024) if lines can exceed 64 KB (otherwise Scan() stops early with bufio.ErrTooLong).
💡 Tip
Accept io.Reader instead of a file path in your parsers (func ParseCSV(r io.Reader)). Unit tests can then pass strings.NewReader("a,b\n1,2\n") directly in memory with zero temp files.
Common mistakes
- Ignoring
file.Close()'s error when writing files: Buffered OS writes can report disk-full errors only whenClose()flushes—checkif err := f.Close(); err != nilon writable files! - Forgetting
defer resp.Body.Close()on HTTP client calls: Leaves the underlying TCP socket out ofhttp.Transport's keep-alive pool. - Calling
io.ReadAll(r.Body)without a size limit: Lets one client trigger an OOM kill with a giant payload.
⚠ Warning
Never assume io.LimitReader(r, limit) returns an error when the input exceeds limit—it silently truncates at limit bytes. Use http.MaxBytesReader in HTTP handlers or read limit + 1 bytes when truncation must be rejected.
What happens if you skip this
Handlers built around io.ReadAll and os.ReadFile pass small local tests, then crash with OOM errors in production as soon as users upload large exports or concurrent requests overlap.
Related course: Go Intermediate.
About
Read large text streams line by line with bufio.Scanner, copy streams in bounded memory with io.Copy, and cap untrusted HTTP bodies with io.LimitReader. After this, large payloads will not exhaust RAM.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.