GCP & Backend Engineer Guide: Cursor-Checkpointed Batch Backfills in Datastore
In Google Cloud Datastore (and Firestore in Datastore Mode), adding a new composite index in `index.yaml` or removing an `noindex` tag in a Go struct does not retroactively index existing historical entities until each entity is re-read and re-put. Worse, running a naive backfill query with `OFFSET` or holding a single query iterator open across 20 million entities fails with `InvalidArgument: query cursor expired` after 30–60 minutes. As a GCP engineer and backend engineer, I build cursor-checkpointed, rate-limited batch re-indexing workers in Go.
1. Cursor-Checkpointed Batch Iteration & 500-Entity PutMulti Chunks in Go
Instead of `OFFSET` (which bills read operations for every skipped entity), we query 400 entities per page, extract the opaque ` datastore.Cursor` after each batch, persist the cursor checkpoint so interrupted jobs resume cleanly, and write back entities in `PutMulti` chunks well under Datastore's 500-entity / 10MB mutation limit:
// backfill/datastore_reindex.go
package backfill
import (
"context"
"errors"
"time"
"cloud.google.com/go/datastore"
"google.golang.org/api/iterator"
)
const PageSize = 400
func ReindexKindPage(ctx context.Context, client *datastore.Client, kind, cursorStr string) (nextCursor string, processed int, err error) {
q := datastore.NewQuery(kind).Limit(PageSize)
if cursorStr != "" {
cur, err := datastore.DecodeCursor(cursorStr)
if err != nil {
return "", 0, err
}
q = q.Start(cur)
}
var (
keys []*datastore.Key
entities []datastore.PropertyList
)
it := client.Run(ctx, q)
for {
var props datastore.PropertyList
key, err := it.Next(&props)
if errors.Is(err, iterator.Done) {
break
}
if err != nil {
return "", 0, err
}
keys = append(keys, key)
entities = append(entities, props)
}
if len(keys) == 0 {
return "", 0, nil // Backfill complete
}
cur, err := it.Cursor()
if err != nil {
return "", 0, err
}
// Re-Put entities to trigger index population on newly indexed properties
if _, err := client.PutMulti(ctx, keys, entities); err != nil {
return "", 0, err
}
time.Sleep(50 * time.Millisecond) // Smooth tablet write pressure
return cur.String(), len(keys), nil
}
2. Avoiding Hot-Spotting on Monotonically Increasing Keys
Because Datastore splits tablets by key ranges, running a sequential key-ordered backfill at 10,000 writes/sec hammers one Bigtable tablet at a time. Throttling each worker or sharding ranges across hex key prefixes (`00`..`ff`) distributes write load evenly across the cluster.