Your microservice returns HTTP 200, but downstream consumers fail to parse payloads because an array field suddenly swapped from [] to null. Worse, two concurrent requests to the same endpoint occasionally mutate each other’s response payloads before they reach the wire, corrupting production data silently without triggering panic logs.
Both issues stem from how Go manages slices under the hood: slice headers are simple structs containing a pointer, a length, and a capacity.
text{"user_id": 104, "tags": null}
Instead of:
text{"user_id": 104, "tags": []}
The consumer expected a valid list. It got a null pointer exception instead.
The Underlying Mechanism
A Go slice does not own data directly. It is a three-word header:
gotype slice struct {
array unsafe.Pointer
len int
cap int
}
When you define var s []string, the header has array = nil, len = 0, and cap = 0. This is a nil slice.
When you define s := []string{} or s := make([]string, 0), the header has array = &zerobase (an allocation pointer), len = 0, and cap = 0. This is an empty, non-nil slice.
In pure Go logic, len(s) is 0 for both. A range loop treats both identically. But Go’s standard library encoding/json serializes them differently. A nil slice serializes to the JSON token null. A non-nil empty slice serializes to [].
The second failure, silent payload corruption, happens when you derive sub-slices from an existing buffer and use append(). If the underlying array has leftover capacity, append does not allocate a new backing array. It overwrites the next index of the shared array.
gopackage main
import (
"bytes"
"encoding/json"
"fmt"
)
type Record struct {
ID int `json:"id"`
Tags []string `json:"tags"`
}
func getTags(filter bool) []string {
if filter {
return []string{"admin"}
}
// Nil slice returned when no tags match
var tags []string
return tags
}
func main() {
r := Record{
ID: 1,
Tags: getTags(false),
}
out, _ := json.Marshal(r)
fmt.Println(string(out))
}
Run this code:
text{"id":1,"tags":null}
Now consider capacity aliasing in a shared buffer or cache:
gopackage main
import "fmt"
func process(prefix []byte) {
// Worker A takes a sub-slice and appends
workerA := append(prefix, 'A')
// Worker B takes the same sub-slice and appends
workerB := append(prefix, 'B')
fmt.Printf("Worker A: %s\n", string(workerA))
fmt.Printf("Worker B: %s\n", string(workerB))
}
func main() {
// Underlying array has cap=8, len=3
buf := make([]byte, 3, 8)
copy(buf, "raw")
process(buf)
}
Output:
textWorker A: rawB
Worker B: rawB
workerB overwrote workerA’s byte because buf had five unused capacity slots. append saw available capacity at index 3, wrote into it, and returned a slice header pointing to the exact same array memory.
Fixing Nil vs Empty JSON Serialization
If your API contract requires an array in the JSON schema, you cannot let repository or domain layers return a nil slice directly to your HTTP serializer.
There are three ways to handle this cleanly.
1. Initialize Slices with Non-Zero Allocation
Initialize using make with length 0, or instantiate an empty literal.
gofunc QueryTags(userID int64) []string {
tags := make([]string, 0)
rows, err := db.Query("SELECT tag FROM user_tags WHERE user_id = ?", userID)
if err != nil {
return tags
}
defer rows.Close()
for rows.Next() {
var t string
if err := rows.Scan(&t); err == nil {
tags = append(tags, t)
}
}
return tags
}
If zero rows are found, tags still retains a valid pointer. When serialized, it produces [].
2. Custom JSON Marshalling
When using third-party packages or generated code where you cannot control how slices are initialized, implement json.Marshaler on the containing struct, or normalize before marshal.
gotype ProfileResponse struct {
Username string `json:"username"`
Roles []string `json:"roles"`
}
func (p ProfileResponse) MarshalJSON() ([]byte, error) {
type Alias ProfileResponse
roles := p.Roles
if roles == nil {
roles = []string{}
}
return json.Marshal(&struct {
Alias
Roles []string `json:"roles"`
}{
Alias: Alias(p),
Roles: roles,
})
}
The alias type prevents infinite recursion during MarshalJSON.
Fixing Capacity Aliasing with Full Slice Expressions
When you pass a slice to another function or goroutine, or create a working sub-slice from a cached byte buffer, limit the capacity using Go’s 3-index slicing syntax: slice[low:high:max].
This sets the sub-slice capacity explicitly to max - low.
gopackage main
import "fmt"
func processFixed(prefix []byte) {
// Set cap equal to len so append is forced to allocate a new backing array
sub := prefix[0:3:3]
workerA := append(sub, 'A')
workerB := append(sub, 'B')
fmt.Printf("Worker A: %s\n", string(workerA))
fmt.Printf("Worker B: %s\n", string(workerB))
}
func main() {
buf := make([]byte, 3, 8)
copy(buf, "raw")
processFixed(buf)
}
Output:
textWorker A: rawA
Worker B: rawB
By clamping the capacity to 3 with prefix[0:3:3], workerA sees len = 3 and cap = 3. When append runs, it detects that the sub-slice has no spare capacity. It allocates a distinct backing array on the heap and copies the prefix over. workerB does the same. Neither worker overwrites the other.
Edge Case: The sync.Pool Buffer Trap
A common performance pattern in high-throughput Go services involves recycling byte buffers using sync.Pool. If you mix capacity aliasing with buffer reuse, you introduce subtle memory races that escape standard unit tests.
Look at this faulty implementation:
govar bufferPool = sync.Pool{
New: func() any {
b := make([]byte, 0, 1024)
return &b
},
}
func FormatLog(event string, payload []byte) []byte {
bp := bufferPool.Get().(*[]byte)
buf := (*bp)[:0]
buf = append(buf, []byte(event)...)
buf = append(buf, ':')
buf = append(buf, ' ')
// Dangerous: returning a sub-slice derived from a pooled backing array
result := append(buf, payload...)
// Buffer put back while result is still in use downstream
*bp = buf
bufferPool.Put(bp)
return result
}
The Breakdown
FormatLogtakes a pooled buffer with capacity 1024.- It constructs the message and returns
result. resultshares the backing array withbuf.- The buffer is returned to
bufferPool. - Another goroutine retrieves that same buffer from
bufferPooland overwrites the contents while the caller ofFormatLogis still writingresultto a socket or file.
The Fix
Never return a slice whose backing array is owned by a sync.Pool. If you must return an owned byte slice to a caller outside the pooling scope, allocate a fresh slice or accept a destination writer:
gofunc WriteLog(w io.Writer, event string, payload []byte) error {
bp := bufferPool.Get().(*[]byte)
buf := (*bp)[:0]
defer func() {
*bp = buf
bufferPool.Put(bp)
}()
buf = append(buf, []byte(event)...)
buf = append(buf, ':')
buf = append(buf, ' ')
buf = append(buf, payload...)
_, err := w.Write(buf)
return err
}
Now the pooled slice never escapes the lifetime of WriteLog.
Edge Case: Deserializing JSON Arrays into Existing Slices
json.Unmarshal does not clear an existing slice before decoding into it. It reuses the backing array and appends or overwrites indices based on the input length.
gopackage main
import (
"encoding/json"
"fmt"
)
type Data struct {
Items []int `json:"items"`
}
func main() {
payload1 := []byte(`{"items": [1, 2, 3]}`)
payload2 := []byte(`{"items": [9]}`)
var d Data
_ = json.Unmarshal(payload1, &d)
fmt.Printf("First unmarshal: %v\n", d.Items)
// Reusing the struct instance without reinitializing
_ = json.Unmarshal(payload2, &d)
fmt.Printf("Second unmarshal: %v\n", d.Items)
}
Output:
textFirst unmarshal: [1 2 3]
Second unmarshal: [9 2 3]
json.Unmarshal saw that d.Items had a length of 3. It overwrote index 0 with the value 9 and left indices 1 and 2 intact.
To avoid this, reset the slice to nil or allocate a clean instance of the destination struct before calling json.Unmarshal:
god = Data{}
err := json.Unmarshal(payload2, &d)
Now d.Items evaluates accurately to [9].
Verification and Testing
Write a test that specifically executes concurrent reads and writes on slices created from shared slices, and use the race detector to catch aliasing mistakes.
Save this as slice_test.go:
gopackage main
import (
"bytes"
"encoding/json"
"testing"
)
type Payload struct {
Tags []string `json:"tags"`
}
func TestNilVsEmptySliceJSON(t *testing.T) {
var nilSlice []string
emptySlice := make([]string, 0)
p1 := Payload{Tags: nilSlice}
p2 := Payload{Tags: emptySlice}
b1, err := json.Marshal(p1)
if err != nil {
t.Fatal(err)
}
b2, err := json.Marshal(p2)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(b1, []byte(`{"tags":null}`)) {
t.Fatalf("expected null tags, got: %s", b1)
}
if !bytes.Equal(b2, []byte(`{"tags":[]}`)) {
t.Fatalf("expected empty array tags, got: %s", b2)
}
}
func TestSliceCapacityAliasing(t *testing.T) {
parent := make([]int, 2, 4)
parent[0] = 10
parent[1] = 20
// Use 3-index slice to enforce copy-on-write via append
childA := append(parent[0:2:2], 30)
childB := append(parent[0:2:2], 40)
if childA[2] == childB[2] {
t.Fatalf("capacity aliasing detected: childA[2]=%d overwrote childB[2]=%d", childA[2], childB[2])
}
}
Run the tests with the race detector enabled:
bashgo test -v -race ./...
Expected output:
text=== RUN TestNilVsEmptySliceJSON
--- PASS: TestNilVsEmptySliceJSON (0.00s)
=== RUN TestSliceCapacityAliasing
--- PASS: TestSliceCapacityAliasing (0.00s)
PASS
ok command-line-arguments 0.024s
When writing Go, treat slice headers as value types containing pointers. The moment a slice has spare capacity (len < cap), appending to it modifies the memory address that other slices pointing to the same array can read. Use 3-index slicing to cut off excess capacity, and explicitly allocate empty slices when your serialized output demands an empty collection instead of a null.