Schema-first GraphQL in Go with gqlgen: generating resolvers, batching N+1 lookups with a per-request dataloader, limiting query complexity, turning off introspection in production, and serving it next to the rest of your backend.

A GraphQL API in Go is usually built with gqlgen: you write the schema, gqlgen generates the executable schema and resolver stubs in Go, and you fill in the resolvers. The generated code is type-checked against your models, so a field that changes type in the schema breaks the build instead of a client.
Generating the server is only a start: production GraphQL also needs batching for the lookups that turn one query into a hundred database calls, a complexity limit so one request cannot ask for everything, introspection that is off where it should be, and the services and databases the resolvers read from.
This guide builds a small book catalog API. It starts with Encore, where the GraphQL handler is one service and the data lives in another, and then shows the same gqlgen server on net/http.
Encore is a backend framework with built-in infrastructure, and its GraphQL tutorial uses gqlgen. The GraphQL layer is a service with one raw endpoint, and resolvers fetch data by calling other services as ordinary Go functions, so the catalog service can own its database while the GraphQL service only shapes responses.

Run in your terminal to get started locally.
The catalog service exposes two private endpoints. AuthorsByIDs takes a list of IDs, which is what lets the GraphQL layer fetch every author for a page in one call. The data is in memory to keep the example short; in an app both endpoints are SQL queries against the service's database:
// Service catalog owns books and authors.
package catalog
import (
"context"
"encore.dev/rlog"
)
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
AuthorID string `json:"author_id"`
}
type Author struct {
ID string `json:"id"`
Name string `json:"name"`
}
type BookList struct {
Books []*Book `json:"books"`
}
type AuthorIDs struct {
IDs []string `json:"ids"`
}
type AuthorList struct {
Authors []*Author `json:"authors"`
}
// In-memory data keeps the example self-contained; in an app these are SQL queries.
var books = []*Book{
{ID: "b1", Title: "The Go Programming Language", AuthorID: "a1"},
{ID: "b2", Title: "Go in Practice", AuthorID: "a2"},
{ID: "b3", Title: "The C Programming Language", AuthorID: "a1"},
}
var authors = map[string]*Author{
"a1": {ID: "a1", Name: "Brian Kernighan"},
"a2": {ID: "a2", Name: "Matt Butcher"},
}
//encore:api private
func ListBooks(ctx context.Context) (*BookList, error) {
return &BookList{Books: books}, nil
}
// AuthorsByIDs is a batch endpoint, so GraphQL can fetch every author in one call.
//
//encore:api private
func AuthorsByIDs(ctx context.Context, p *AuthorIDs) (*AuthorList, error) {
rlog.Info("authors batch", "ids", len(p.IDs))
out := make([]*Author, 0, len(p.IDs))
for _, id := range p.IDs {
if a, ok := authors[id]; ok {
out = append(out, a)
}
}
return &AuthorList{Authors: out}, nil
}
The schema is the contract clients see:
type Query { books: [Book!]! } type Book { id: ID! title: String! author: Author! } type Author { id: ID! name: String! }
autobind tells gqlgen to use the catalog service's Go types as the GraphQL models, and the resolver: true line makes author a resolver field, since a Book only stores AuthorID. Add a tools.go that imports github.com/99designs/gqlgen as the tutorial shows, so the generator stays in go.mod:
schema:
- graphql/*.graphqls
exec:
filename: graphql/generated/generated.go
package: generated
model:
filename: graphql/model/models_gen.go
package: model
resolver:
layout: follow-schema
dir: graphql
package: graphql
autobind:
- "encore.app/catalog"
models:
Book:
fields:
author:
resolver: true
handler.NewDefaultServer is deprecated in current gqlgen releases, so the service builds the server with handler.New and adds only the transports and extensions it needs. The complexity limit rejects expensive queries before any resolver runs, and introspection is only on outside production:
// Service graphql exposes the GraphQL API.
package graphql
import (
"net/http"
"encore.app/graphql/generated"
"encore.dev"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/handler/transport"
)
//go:generate go run github.com/99designs/gqlgen generate
//encore:service
type Service struct {
srv *handler.Server
}
func initService() (*Service, error) {
srv := handler.New(generated.NewExecutableSchema(generated.Config{Resolvers: &Resolver{}}))
srv.AddTransport(transport.GET{})
srv.AddTransport(transport.POST{})
// Reject queries whose computed complexity exceeds 200 before they run.
srv.Use(extension.FixedComplexityLimit(200))
if encore.Meta().Environment.Type != encore.EnvProduction {
srv.Use(extension.Introspection{})
}
return &Service{srv: srv}, nil
}
//encore:api public raw method=GET,POST path=/graphql
func (s *Service) Query(w http.ResponseWriter, req *http.Request) {
// A fresh loader per request batches author lookups without caching across users.
ctx := withLoaders(req.Context())
s.srv.ServeHTTP(w, req.WithContext(ctx))
}
Without batching, a query for 50 books calls AuthorsByIDs 50 times. The loader collects every author ID requested within 2 ms and makes one call; it is created per request, so its cache never serves one user's data to another:
package graphql
import (
"context"
"time"
"encore.app/catalog"
"github.com/vikstrous/dataloadgen"
)
type loadersKey struct{}
type loaders struct {
author *dataloadgen.Loader[string, *catalog.Author]
}
func withLoaders(ctx context.Context) context.Context {
l := &loaders{
author: dataloadgen.NewLoader(fetchAuthors, dataloadgen.WithWait(2*time.Millisecond)),
}
return context.WithValue(ctx, loadersKey{}, l)
}
func loadersFrom(ctx context.Context) *loaders {
return ctx.Value(loadersKey{}).(*loaders)
}
// fetchAuthors receives every author ID requested while the loader waited,
// and must return results in the same order as ids.
func fetchAuthors(ctx context.Context, ids []string) ([]*catalog.Author, []error) {
resp, err := catalog.AuthorsByIDs(ctx, &catalog.AuthorIDs{IDs: ids})
if err != nil {
return nil, []error{err}
}
byID := make(map[string]*catalog.Author, len(resp.Authors))
for _, a := range resp.Authors {
byID[a.ID] = a
}
out := make([]*catalog.Author, len(ids))
errs := make([]error, len(ids))
for i, id := range ids {
if a, ok := byID[id]; ok {
out[i] = a
} else {
errs[i] = ¬FoundError{id: id}
}
}
return out, errs
}
type notFoundError struct{ id string }
func (e *notFoundError) Error() string { return "author " + e.id + " not found" }
Run go run github.com/99designs/gqlgen generate, then fill in the generated stubs:
// graphql/schema.resolvers.go (generated stubs, filled in)
// Author is the resolver for the author field.
func (r *bookResolver) Author(ctx context.Context, obj *catalog.Book) (*catalog.Author, error) {
return loadersFrom(ctx).author.Load(ctx, obj.AuthorID)
}
// Books is the resolver for the books field.
func (r *queryResolver) Books(ctx context.Context) ([]*catalog.Book, error) {
resp, err := catalog.ListBooks(ctx)
if err != nil {
return nil, err
}
return resp.Books, nil
}
We ran this app with encore run. A query for three books and their authors returned all three, and the catalog service logged a single AuthorsByIDs call with two IDs. A query with 70 aliased copies of books was rejected with operation has complexity 280, which exceeds the limit of 200.
Each call from a resolver to the catalog service shows up in Encore's tracing, which is where an N+1 regression becomes visible as a column of identical spans. When the catalog moves to a database, Encore provisions Postgres locally and RDS or Cloud SQL in your AWS or GCP account from the declaration in the catalog service, and the GraphQL service does not change.
Best fit: Go teams that want a GraphQL gateway over several services, with the services' databases and infrastructure declared in the same codebase.
Without Encore, the schema, gqlgen.yml, resolvers and loaders stay the same; the data comes from your own packages instead of service calls, and you write the server. WithLoaders wraps the handler so each request gets fresh loaders:
// main.go
package main
import (
"log"
"net/http"
"os"
"time"
"example.com/shop/graphql"
"example.com/shop/graphql/generated"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/handler/transport"
)
func main() {
srv := handler.New(generated.NewExecutableSchema(generated.Config{Resolvers: &graphql.Resolver{}}))
srv.AddTransport(transport.POST{})
srv.Use(extension.FixedComplexityLimit(200))
if os.Getenv("APP_ENV") != "production" {
srv.Use(extension.Introspection{})
}
mux := http.NewServeMux()
mux.Handle("POST /graphql", graphql.WithLoaders(srv))
s := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 30 * time.Second,
}
log.Fatal(s.ListenAndServe())
}
Set ReadHeaderTimeout and WriteTimeout on the server, since GraphQL requests can be expensive and the zero values mean no timeout. Leave GET out of the transports unless you need persisted queries over GET, because a GET mutation is easier to trigger from another site. For tracing, gqlgen has an extension point (srv.Use) where OpenTelemetry instrumentation plugs in, and your data sources need their own spans.
The database, its migrations, the deployment target and the per-environment config are yours to provision and keep in step.
Best fit: Go services that already have their own deployment and data layer and need a GraphQL endpoint on top.
Use gqlgen in both cases; the schema-first workflow and compile-time checks are what make GraphQL in Go maintainable. Run it on net/http when the GraphQL server sits on top of a data layer and deployment you already have. Pick Encore when the GraphQL API is a gateway over several services and you want those services, their databases and the tracing that exposes N+1 problems to come from the same Go code, deployed to your own AWS or GCP account.
gqlgen is the most widely used. It is schema-first: you write the GraphQL schema, and it generates type-safe Go code and resolver stubs, so a schema change that does not match your resolvers fails to compile. graph-gophers/graphql-go and graphql-go/graphql build the schema at runtime instead, which avoids code generation but moves type errors to runtime.
Use a dataloader. Each field resolver asks the loader for one key, the loader waits a few milliseconds to collect every key requested in that tick, and then calls one batch function, such as SELECT ... WHERE id = ANY($1). Create the loader per request so its cache never leaks data between users.
Yes. For a private API used only by your own clients. Introspection hands anyone the full schema. Public GraphQL APIs often leave it on for tooling. Either way, a query complexity or depth limit matters more: it stops expensive queries regardless of whether the attacker knows the schema.
Yes. A raw endpoint at /graphql hands requests to the gqlgen handler, and resolvers call other services' endpoints as ordinary Go functions. Encore provisions the databases and other infrastructure those services declare, locally and in your own AWS or GCP account.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.