Gin and your data · 6 MIN READ
?include= without N+1 in Gin: one batched loader per relation, a bounded errgroup and list-order output
Serve optional related data on a Gin list endpoint with one batched lookup per relation, bounded concurrent loads and deterministic output, and prove the query count by counting store calls.
A client asks for /posts?include=author,tags so that it can render a feed in one request. The obvious implementation looks up each post's author inside the loop that builds the response, and a page of fifty posts quietly becomes a hundred and one queries. The cost should depend on how many relations were requested, never on how many rows the page holds.
gin · A MAP OF THE IDEA
- Allow-list includes
- Collect the page's IDs
- Batch load, bounded
- Assemble in list order
Useful when
- Round trips stay constant as the page grows.
- Unknown includes fail loudly instead of silently returning less data.
Watch out
- errgroup v0.24.0 does not recover panics, and gin.Recovery cannot catch a loader panic.
- The errgroup context is canceled once Wait returns; never reuse it.
Implementation & operation cost: A batch method per relation in the store, an include registry, and per-request concurrency that claims pool connections.
N+1 grows with the page, batching grows with the request
In the N+1 shape, one query loads the list and then one more query runs per row for each relation. Each extra round trip adds latency in series and holds a pool connection while it waits, so under load the request spends most of its time queuing for connections, as the SQL pool lesson describes. Batching reverses the dependency. Collect the IDs the page refers to, load each relation for all of them in one query, and join the results in memory. The cost becomes one list query plus one query per requested include, whatever the page size. Independent relations can also load concurrently, which turns their latencies from a sum into a maximum, provided the concurrency is bounded.
Includes are an allow-list of loaders
Map each public include name to a loader that fetches one relation for the whole page and writes only its own field of a page struct. That map is the allow-list. An unknown name answers 400 and lists the valid ones, because a typo that silently returns less data is a bug nobody reports. Accept repeated and comma-separated forms through c.QueryArray and drop duplicates; the safe-filters lesson explains when to parse the raw query strictly instead. A loader is also an authorization boundary: an included author must expose exactly the fields a direct read of that author would, for the same caller. Nested includes such as author.organization multiply the work and the data exposed, so support them only deliberately, with a depth limit.
Count the calls: naive versus batched
The store is an in-memory model that counts every method call. The naive route looks up authors one post at a time; the batched route parses the includes, loads the posts, runs the requested loaders through an errgroup limited to two at a time, and assembles the response in post order. A last request makes the tags store fail.
package main
import (
"context"
"errors"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
)
type Post struct {
ID int
AuthorID int
Title string
}
type Author struct {
ID int `json:"id"`
Name string `json:"name"`
}
// Store is an in-memory model of a database. It counts every call so the
// program can show how many round trips one request costs.
type Store struct {
mu sync.Mutex
calls map[string]int
failTags bool
}
func (s *Store) count(name string) {
s.mu.Lock()
defer s.mu.Unlock()
s.calls[name]++
}
func (s *Store) Calls() string {
s.mu.Lock()
defer s.mu.Unlock()
var parts []string
for _, name := range slices.Sorted(maps.Keys(s.calls)) {
parts = append(parts, fmt.Sprintf("%s=%d", name, s.calls[name]))
}
clear(s.calls)
if len(parts) == 0 {
return "none"
}
return strings.Join(parts, " ")
}
var authors = map[int]Author{7: {7, "kestrel"}, 9: {9, "heron"}}
var tags = map[int][]string{1: {"go", "concurrency"}, 3: {"sql"}}
func (s *Store) ListPosts(ctx context.Context) ([]Post, error) {
s.count("ListPosts")
return []Post{{1, 7, "Channels"}, {2, 9, "Interfaces"}, {3, 7, "database/sql"}, {4, 9, "Generics"}}, ctx.Err()
}
// AuthorByID is what a naive include calls once per post.
func (s *Store) AuthorByID(ctx context.Context, id int) (Author, error) {
s.count("AuthorByID")
return authors[id], ctx.Err()
}
// AuthorsByIDs is one round trip for a whole page: WHERE id = ANY($1).
func (s *Store) AuthorsByIDs(ctx context.Context, ids []int) (map[int]Author, error) {
s.count("AuthorsByIDs")
out := map[int]Author{}
for _, id := range ids {
if a, ok := authors[id]; ok {
out[id] = a
}
}
return out, ctx.Err()
}
func (s *Store) TagsByPostIDs(ctx context.Context, ids []int) (map[int][]string, error) {
s.count("TagsByPostIDs")
if s.failTags {
return nil, errors.New("tags replica unavailable")
}
out := map[int][]string{}
for _, id := range ids {
out[id] = slices.Sorted(slices.Values(tags[id]))
}
return out, ctx.Err()
}
type postDTO struct {
ID int `json:"id"`
Title string `json:"title"`
Author *Author `json:"author,omitzero"`
Tags []string `json:"tags,omitzero"`
}
// relations is the allow-list: each include names one batched loader that
// fills only its own field of the page.
type page struct {
posts []Post
authors map[int]Author
tags map[int][]string
}
var relations = map[string]func(context.Context, *Store, *page) error{
"author": func(ctx context.Context, s *Store, p *page) error {
ids := make([]int, 0, len(p.posts))
for _, post := range p.posts {
ids = append(ids, post.AuthorID)
}
slices.Sort(ids)
var err error
p.authors, err = s.AuthorsByIDs(ctx, slices.Compact(ids))
return err
},
"tags": func(ctx context.Context, s *Store, p *page) error {
ids := make([]int, len(p.posts))
for i, post := range p.posts {
ids[i] = post.ID
}
var err error
p.tags, err = s.TagsByPostIDs(ctx, ids)
return err
},
}
func parseIncludes(raw []string) ([]string, error) {
var out []string
for _, v := range raw {
for name := range strings.SplitSeq(v, ",") {
if _, ok := relations[name]; !ok {
return nil, fmt.Errorf("unknown include %q", name)
}
if !slices.Contains(out, name) {
out = append(out, name)
}
}
}
return out, nil
}
func listPosts(s *Store) gin.HandlerFunc {
return func(c *gin.Context) {
includes, err := parseIncludes(c.QueryArray("include"))
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error(),
"allowed": slices.Sorted(maps.Keys(relations))})
return
}
ctx := c.Request.Context() // goroutines get this, never c
posts, err := s.ListPosts(ctx)
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
p := &page{posts: posts}
g, gctx := errgroup.WithContext(ctx)
g.SetLimit(2) // at most two relation queries hold pool connections at once
for _, name := range includes {
load := relations[name]
g.Go(func() error { return load(gctx, s, p) })
}
if err := g.Wait(); err != nil { // gctx is canceled from here on
c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "related data unavailable"})
return
}
out := make([]postDTO, len(posts)) // response order is the order of posts
for i, post := range posts {
out[i] = postDTO{ID: post.ID, Title: post.Title}
if a, ok := p.authors[post.AuthorID]; ok {
out[i].Author = &a
}
if p.tags != nil {
out[i].Tags = append([]string{}, p.tags[post.ID]...) // [] when included but empty
}
}
c.JSON(http.StatusOK, gin.H{"posts": out})
}
}
// naiveAuthors is the N+1 shape: one query for the list, one per row.
func naiveAuthors(s *Store) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
posts, _ := s.ListPosts(ctx)
names := make([]string, len(posts))
for i, post := range posts {
a, _ := s.AuthorByID(ctx, post.AuthorID)
names[i] = a.Name
}
c.JSON(http.StatusOK, gin.H{"authors": names})
}
}
func main() {
gin.SetMode(gin.TestMode)
s := &Store{calls: map[string]int{}}
r := gin.New()
r.GET("/posts", listPosts(s))
r.GET("/naive/posts", naiveAuthors(s))
get := func(target string, showBody bool) {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))
fmt.Printf("GET %s -> %d, store calls: %s\n", target, w.Code, s.Calls())
if showBody {
fmt.Println(" ", w.Body.String())
}
}
get("/naive/posts", false)
get("/posts", false)
get("/posts?include=author", false)
get("/posts?include=author,tags&include=author", true)
get("/posts?include=author,reviews", true)
s.failTags = true
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/posts?include=tags", nil))
fmt.Println("tags store failing ->", w.Code, w.Body.String())
}The naive route makes one AuthorByID call per post, four for four posts, and that number grows with the page. The batched route makes one ListPosts call and one call per requested relation: AuthorsByIDs receives the deduplicated, sorted author IDs 7 and 9, and TagsByPostIDs receives every post ID. include=author,tags&include=author shows repeated and comma-separated forms merged with duplicates dropped. Each loader writes only its own field of page, so the goroutines never write the same memory, and they receive gctx rather than c. The response is built after Wait, in post order. A post without tags renders [] because the slice is non-nil, while a relation that was not requested is omitted by omitzero. An unknown include fails before any store call, and a failing loader turns into 503 with no partial body.
Bounded concurrency with errgroup, and what it does not cover
errgroup.WithContext(c.Request.Context()) gives the loaders a context that is canceled when the client leaves and, through context.WithCancelCause in x/sync v0.24.0, the first time a loader returns an error, so the other loaders can stop early. Wait returns that first error. SetLimit(2) must be called before the first Go, because changing the limit while goroutines are active panics; once the limit is reached, Go blocks the handler until a slot frees. Size the limit against the connection pool: concurrent requests times loaders per request is how many connections includes can claim. Two traps are specific to running this inside Gin. The derived context is canceled as soon as Wait returns, so rendering or a follow-up query must use the request context, not gctx. And in v0.24.0, Go does not recover panics: a panic in a loader goroutine crashes the process, because gin.Recovery only protects the goroutine running the handler chain.
One query per relation in SQL, ordered by the database
In PostgreSQL each loader becomes a single statement over an array of IDs. Let the database order the rows so that each slice arrives sorted, and build the response from the primary list, never by ranging over a map. Decide explicitly what a missing related row means: a deleted author can render as null, drop the post or fail the request, and each choice belongs in the API contract. Bound the ID list through the page limit; a page of at most 100 rows can never send more than 100 IDs to a loader.
// TagsByPostIDs is one round trip for the whole page, ordered by the database.
func (s *PG) TagsByPostIDs(ctx context.Context, ids []int64) (map[int64][]string, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT post_id, tag FROM post_tags WHERE post_id = ANY($1) ORDER BY post_id, tag`, ids)
if err != nil {
return nil, err
}
defer rows.Close()
out := make(map[int64][]string, len(ids))
for rows.Next() {
var id int64
var tag string
if err := rows.Scan(&id, &tag); err != nil {
return nil, err
}
out[id] = append(out[id], tag)
}
return out, rows.Err()
}This fragment runs against a real PostgreSQL database in your own environment; PG wraps a *sql.DB. post_id = ANY($1) takes the whole ID list as one array parameter. With the pgx stdlib driver a []int64 argument is encoded as an array directly, while lib/pq needs pq.Array(ids). ORDER BY post_id, tag makes every slice deterministic without sorting in Go. rows.Err is checked after the loop because iteration can fail midway, as the SQL rows lesson explains.
Make the call count a test assertion
Latency tests rarely catch an N+1 regression on a laptop with ten rows. A call count does. Run the list handler against a counting store with page sizes of 1, 10 and 50 and assert that the number of calls per relation is identical and equal to one. Add cases for an unknown include, a duplicated include, an included relation with no rows, a loader that fails and a client that cancels mid-request, and run the suite under go test -race so a loader that touches c or shares a map is reported. In production, record the number of queries per request as a span attribute or histogram, keyed by route template, so a regression shows up as a step in a graph rather than as a slow page.
TAKE THIS WITH YOU
Map each include to one batched loader keyed by the page's IDs, run the loaders through a bounded errgroup on the request context, and build the response in list order after Wait.
Check your understanding
A client requests a page of 50 posts with ?include=author,tags. With batched loaders, how many store calls should the request make?
Go to the source
Progress stays in this browser. No account needed.