{
  "id": "go",
  "title": "Redis feature store with go-redis",
  "url": "https://redis.io/docs/latest/develop/use-cases/feature-store/go/",
  "summary": "Build a Redis-backed online feature store in Go with go-redis",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-06-04T14:49:57+01:00",
  "children": [],
  "page_type": "content",
  "content_hash": "d87a77d7d9d1c9d27c2b93e592e801d1a7297e271e25e7814669f6e4afcc5086",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This guide shows you how to build a small Redis-backed online feature store in\nGo with [`go-redis`](https://redis.io/docs/latest/develop/clients/go). It includes a\nlocal web server built with Go's standard `net/http` package so you can\nbulk-load a batch of users with a key-level TTL, run a streaming worker that\noverwrites real-time features with per-field TTL, retrieve any subset of\nfeatures for one user under 1 ms, and pipeline `HMGET` across a hundred users\nfor batch scoring."
    },
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Each entity (here, a user) is one Redis\n[Hash](https://redis.io/docs/latest/develop/data-types/hashes) at a deterministic key —\n`fs:user:{id}`. The hash holds every feature for that entity as one field per\nfeature: batch-materialized aggregates (refreshed once a day) alongside\nstreaming-updated signals (refreshed every few seconds). One\n[`HMGET`](https://redis.io/docs/latest/commands/hmget) returns whichever subset the model\nneeds in one network round trip.\n\nTwo TTL layers solve the *mixed staleness* problem without an application-side\ncleaner:\n\n* A **key-level** [`EXPIRE`](https://redis.io/docs/latest/commands/expire) aligned with the\n  batch materialization cycle (24 hours in the demo). If the batch refresher\n  fails, the whole entity disappears at the next cycle and inference sees a\n  missing entity — which the model handler can detect and fall back on —\n  rather than silently outdated values.\n* A **per-field** [`HEXPIRE`](https://redis.io/docs/latest/commands/hexpire) (Redis 7.4+) on\n  each streaming feature gives that field its own shorter expiry, independent\n  of the rest of the hash. If the streaming pipeline stops updating a feature,\n  the field self-cleans while the batch fields stay populated.\n\nIn this example, the batch features describe a user's longer-term shape\n(`country_iso`, `risk_segment`, `account_age_days`, `tx_count_7d`,\n`avg_amount_30d`, `chargeback_count_180d`) and are bulk-loaded by\n`build_features.go` — the demo's stand-in for a nightly Spark / Feast\nmaterialization job. The streaming features describe what the user is doing\nright now (`last_login_ts`, `last_device_id`, `tx_count_5m`,\n`failed_logins_15m`, `session_country`) and are written by\n`streaming_worker.go` — the demo's stand-in for a Flink / Kafka Streams job.\nThe inference handlers of the demo server read any subset of those features\nthrough `feature_store.go`'s helper type.\n\nThat gives you:\n\n* A single round trip for retrieval — any subset of features for one entity in\n  one [`HMGET`](https://redis.io/docs/latest/commands/hmget).\n* Sub-millisecond hot path. The Redis-side work is microseconds; in practice\n  the bottleneck is the network round trip plus the model's own feature-prep.\n* Pipelined batch scoring — one round trip for `N` users at once.\n* Independent freshness per feature, expressed as a server-side TTL rather\n  than as application logic.\n* Self-cleanup on pipeline failure: a stalled batch refresher lets entities\n  expire on schedule, and a stalled streaming worker lets each affected field\n  expire on its own timer."
    },
    {
      "id": "how-it-works",
      "title": "How it works",
      "role": "content",
      "text": "There are three paths: a **batch path** that bulk-loads features once per\nmaterialization cycle, a **streaming path** that updates real-time features\nas events arrive, and an **inference path** that reads features on the\nrequest side."
    },
    {
      "id": "batch-path-per-materialization-cycle",
      "title": "Batch path (per materialization cycle)",
      "role": "content",
      "text": "1. The batch job calls `SynthesizeUsers(N, seed)` (in production, the\n   equivalent computation lives in an offline pipeline against the warehouse).\n   The result is `map[string]FeatureMap` for every user in this cycle.\n2. `store.BulkLoad(ctx, rows, ttl)` batches one\n   [`HSET`](https://redis.io/docs/latest/commands/hset) plus one\n   [`EXPIRE`](https://redis.io/docs/latest/commands/expire) per user through go-redis's\n   [`Pipeline`](https://redis.io/docs/latest/develop/clients/go/transpipe), so the whole\n   batch ships in a single round trip. The `HSET` writes every batch field;\n   the `EXPIRE` is what makes the entity disappear if the next batch run\n   fails, so inference reads a missing entity rather than silently outdated\n   values."
    },
    {
      "id": "streaming-path-per-event",
      "title": "Streaming path (per event)",
      "role": "content",
      "text": "When a user does something (login, transaction, page view) the streaming\nlayer computes whatever real-time signals fall out of that event and calls\n`store.UpdateStreaming(ctx, userID, fields, ttl)`. That batches:\n\n1. An [`HSET`](https://redis.io/docs/latest/commands/hset) writing the new field values.\n   Redis is single-threaded per shard, so this is atomic against any\n   concurrent batch write on the same hash — no version columns, no locks.\n2. An [`HEXPIRE`](https://redis.io/docs/latest/commands/hexpire) over exactly the fields\n   that were written, with the streaming TTL. Each streaming field carries\n   its own per-field expiry independent of the rest of the hash. Stop the\n   worker and these fields drop out one by one as their TTLs elapse, while\n   the batch fields remain populated under the longer key-level TTL."
    },
    {
      "id": "inference-path-per-request",
      "title": "Inference path (per request)",
      "role": "content",
      "text": "1. The model server picks the feature subset it needs (the schema is owned by\n   the model, not the store).\n2. It calls `store.GetFeatures(ctx, userID, names)`, which is one\n   [`HMGET`](https://redis.io/docs/latest/commands/hmget). Redis returns the values in\n   the same order as the requested fields, with `nil` for any field that\n   doesn't exist (or has expired).\n3. For batch inference, the model server calls\n   `store.BatchGetFeatures(ctx, userIDs, names)`, which pipelines one\n   [`HMGET`](https://redis.io/docs/latest/commands/hmget) per user across all `N` users\n   in a single network round trip."
    },
    {
      "id": "the-feature-store-helper",
      "title": "The feature-store helper",
      "role": "content",
      "text": "The `FeatureStore` type wraps the read/write paths\n([source](https://github.com/redis/docs/blob/main/content/develop/use-cases/feature-store/go/feature_store.go)):\n\n[code example]"
    },
    {
      "id": "package-layout",
      "title": "Package layout",
      "role": "content",
      "text": "Go won't let `package main` live in the same directory as another package, so\nthe runnable entry points live in `cmd/`:\n\n[code example]\n\nBuild and run with `go run ./cmd/demo_server`. The shim is the only `main`\npackage; everything else is library code."
    },
    {
      "id": "data-model",
      "title": "Data model",
      "role": "content",
      "text": "Each user is one Redis Hash. Every value is stored as a string — Redis hash\nfields are bytes on the wire, so the helper encodes booleans as `\"true\"` /\n`\"false\"` and renders numbers with `strconv`. The model server is responsible\nfor parsing back to the right type, the same way it would when reading any\nserialized feature store.\n\n[code example]\n\nThe batch fields sit under the key-level `EXPIRE`. The streaming fields each\ncarry their own [`HEXPIRE`](https://redis.io/docs/latest/commands/hexpire). If the\nstreaming pipeline stops, the streaming fields drop one by one as their\nper-field TTLs elapse; the batch fields stay until the daily key-level\n`EXPIRE` fires (or the next batch cycle re-pins them)."
    },
    {
      "id": "bulk-loading-batch-features",
      "title": "Bulk-loading batch features",
      "role": "content",
      "text": "`BulkLoad` pipelines one `HSET` and one `EXPIRE` per user. With 500 users\nthat's 1000 commands in one network call — Redis processes them sequentially\non the server side but the client only pays one RTT.\n\n[code example]\n\ngo-redis's `Pipeline` is a *non-transactional* batch: commands queue up and\nship in one round trip, but they don't run inside a `MULTI/EXEC` block.\nThat's the right choice here because each user's `HSET` + `EXPIRE` pair is\nindependent of every other user's, and an all-or-nothing transaction would\nblock the server for the duration of the batch. For the rare case where the\npair has to be inseparable (a server crash between the two would leave the\nentity without a key-level TTL) you would wrap each user in `rdb.TxPipeline()`\nor a Lua script (see [`EVAL`](https://redis.io/docs/latest/commands/eval) /\n[Eval scripting](https://redis.io/docs/latest/develop/programmability/eval-intro)). For\na daily ingestion job that runs end-to-end every cycle, the next run re-pins\nthe TTL — no extra machinery needed.\n\nIn production, the equivalent of this script runs as an offline pipeline (a\nSpark or Feast `materialize` job) that reads from the warehouse and writes\ninto Redis. The\n[Feast `RedisOnlineStore`](https://docs.feast.dev/reference/online-stores/redis)\nprovider does exactly this under the hood; the in-house\n[Redis Feature Form](https://redis.io/docs/latest/develop/ai/featureform) integration\ncovers the materialize + serve path end-to-end."
    },
    {
      "id": "streaming-writes-with-per-field-ttl",
      "title": "Streaming writes with per-field TTL",
      "role": "content",
      "text": "`UpdateStreaming` is the linchpin of the mixed-staleness story:\n\n[code example]\n\n[`HEXPIRE`](https://redis.io/docs/latest/commands/hexpire) sets the TTL on *individual*\nhash fields, not on the whole key. The two commands are sent in one round\ntrip and Redis executes them in pipeline order: the `HSET` runs first and\ncreates or overwrites the fields, then `HEXPIRE` attaches a TTL to each of\nthose same fields. `HEXPIRE` returns one status code per field — `1` if the\nTTL was set, `2` if the expiry was 0 or in the past (so Redis deleted the\nfield instead), `0` if an `NX | XX | GT | LT` conditional flag was set and\nnot met (we never use one here), `-2` if the field doesn't exist on the key.\nThe helper returns an error if any code is anything other than `1`, so the\n\"every streaming write renews its TTL\" invariant fails loudly rather than\nsilently leaving a streaming field with no expiry attached.\n\nIf a streaming pipeline stops, the streaming fields drop out one by one as\ntheir per-field TTLs elapse — there is no application-side cleaner involved.\n[`HTTL`](https://redis.io/docs/latest/commands/httl) lets the model side inspect the\nremaining TTL on any field, which is useful both for debugging (\"why is this\nfeature missing?\" → \"it expired three seconds ago\") and as a freshness signal\nin the model itself.\n\n> **HEXPIRE requires Redis 7.4 or later.** `HEXPIRE` and the field-level TTL\n> commands (`HTTL`, `HPERSIST`, `HEXPIREAT`, `HPEXPIRE`, `HPEXPIREAT`,\n> `HPTTL`, `HEXPIRETIME`, `HPEXPIRETIME`) were added in Redis 7.4. On older\n> Redis builds you would have to put streaming features on their own keys\n> (one key per feature, or one key per feature group) and set a key-level\n> `EXPIRE` instead — at the cost of giving up the single-`HMGET` retrieval."
    },
    {
      "id": "inference-reads-with-hmget",
      "title": "Inference reads with HMGET",
      "role": "content",
      "text": "`GetFeatures` is one `HMGET`:\n\n[code example]\n\nThe model knows exactly which features it consumes, so the request path\nalways takes the `HMGET` branch with an explicit field list — that's the\nsub-millisecond path. `HGETALL` is the right call for debugging (which is\nwhat the demo's \"Inspect\" panel does) but not for serving: it forces Redis\nto serialize every field, including ones the model doesn't need.\n\nFields that don't exist (because they were never written, or because they\nexpired) come back as `nil` (a typed `nil`, not a `string` empty). The helper\ndrops them from the result map so the caller sees only the features that\nare actually available. A real model server would either treat missing\nvalues as a feature (\"this user has no streaming signal yet\") or fall back\nto a default from the model's training data."
    },
    {
      "id": "batch-scoring-with-pipelined-hmget",
      "title": "Batch scoring with pipelined HMGET",
      "role": "content",
      "text": "For batch inference, the same `HMGET` shape pipelines across users:\n\n[code example]\n\nOne round trip for the whole batch — the demo regularly returns 100 users in\n1-2 ms against a local Redis. On a real network the round trip dominates;\npipelining is what keeps batch scoring practical.\n\nA Redis Cluster is different in two ways: a single `Pipeline.Exec` is bound\nto one shard, because non-cross-slot pipelines can only target one node; and\nthe keys for a typical user batch will land on multiple shards. For batch\nreads on a cluster, use the\n[`ClusterClient`](https://redis.io/docs/latest/develop/clients/go/connect) — its\n`Pipeline` knows how to dispatch per-shard, so you pay one round trip per\nshard rather than one for the whole batch. A hash tag like\n`fs:user:{vip}:u0001` forces a known set of keys onto the same shard so one\npipeline can cover all of them in a single round trip."
    },
    {
      "id": "the-streaming-worker",
      "title": "The streaming worker",
      "role": "content",
      "text": "`streaming_worker.go` is the demo's stand-in for whatever Flink, Kafka\nStreams, or bespoke service computes the real-time features\n([source](https://github.com/redis/docs/blob/main/content/develop/use-cases/feature-store/go/streaming_worker.go)).\nIt runs as a goroutine next to the demo server so the UI can start, pause,\nand resume it; in production this code would live in the streaming layer.\n\nEvery tick the worker picks a few random users, generates a new value for\neach streaming feature, and calls `store.UpdateStreaming(ctx, userID, fields, 0)`.\nThe demo defaults to 5 users per tick at 1-second intervals — so a 200-user\nstore sees roughly half its users refreshed in the first minute, and most\nafter a few minutes. Raise `--users-per-tick` or drop `--seed-users` if\nyou'd rather touch every user quickly.\n\n[code example]\n\nPausing the worker is what shows off the mixed-staleness behavior: leave it\npaused for longer than `streamingTTL` and the streaming fields disappear\nfrom every user's hash one by one, while the batch fields remain under the\nlonger key-level `EXPIRE`. The demo's `Pause / resume` button lets you see\nthis happen in real time.\n\n`Pause()` only blocks *future* ticks from running — the goroutine simply\nskips its turn on the next ticker fire. A reset that's about to `DEL` every\nkey needs to wait out an already-running tick too, which is what\n`WaitForIdle()` is for: the demo's `Reset` handler calls `worker.Pause()`\n*and* `worker.WaitForIdle()` before it issues the `DEL` sweep, so a\nmid-flight tick can't recreate a user under a streaming-only hash with no\nkey-level TTL."
    },
    {
      "id": "the-batch-builder",
      "title": "The batch builder",
      "role": "content",
      "text": "`build_features.go` is the demo's nightly materializer\n([source](https://github.com/redis/docs/blob/main/content/develop/use-cases/feature-store/go/build_features.go)).\nIt generates synthetic feature rows and calls `store.BulkLoad` once. The\nsynthesis itself is not the point — in a real deployment the equivalent\ncode reads from the offline store (Snowflake, BigQuery, Iceberg) and writes\nthe resulting hashes into Redis.\n\n[code example]\n\nYou can run the builder on its own (independently of the demo server) to\npopulate Redis from the command line:\n\n[code example]\n\nThat writes 500 users at `fs:user:*` with a one-hour key-level TTL, which is\nhow a typical operator would pre-seed a feature store from the command line\nwhen debugging."
    },
    {
      "id": "the-interactive-demo",
      "title": "The interactive demo",
      "role": "content",
      "text": "`demo_server.go` runs a `net/http` server on port 8087. The HTML page lets\nyou:\n\n* **Bulk-load** any number of users (default 200) with a configurable\n  key-level TTL. Drop the TTL to 30 s and watch the entire store expire on\n  schedule — the same thing that happens if a daily refresher fails.\n* See the **store state** at a glance: user count, batch / streaming TTLs,\n  cumulative read/write counters.\n* See the **streaming worker** status (running / paused, ticks completed,\n  writes performed) and **pause or resume** it. Leave it paused for longer\n  than the streaming TTL to watch streaming fields drop out.\n* Run an **inference read** for any user with a chosen feature subset, and\n  see the value, the per-field TTL, and the read latency.\n* Run **batch scoring** with a pipelined `HMGET` across `N` users and see\n  the total elapsed time plus the per-user breakdown.\n* **Inspect** any user's full hash with field-level TTLs and the key-level\n  TTL — the right view for debugging \"why is this feature missing?\" at\n  read time.\n\nThe server holds one `FeatureStore` and one `StreamingWorker` for the\nlifetime of the process. Endpoints:\n\n| Endpoint                  | What it does                                                                        |\n|---------------------------|-------------------------------------------------------------------------------------|\n| `GET  /state`             | User count, TTL config, stats counters, worker status.                              |\n| `POST /bulk-load`         | Pipelined `HSET` + `EXPIRE` over N synthetic users with a chosen TTL.               |\n| `POST /worker/toggle`     | Pause / resume the streaming worker.                                                |\n| `POST /read`              | `HMGET` a chosen feature subset for one user; report latency and per-field TTLs.    |\n| `POST /batch-read`        | Pipeline `HMGET` across N users; report total latency and per-entity field counts.  |\n| `GET  /inspect`           | `HGETALL` + `HTTL` for one user; full hash view with per-field TTLs.                |\n| `POST /reset`             | Drop every user under the key prefix (used by the demo's reset button).             |"
    },
    {
      "id": "prerequisites",
      "title": "Prerequisites",
      "role": "content",
      "text": "* **Redis 7.4 or later.** [`HEXPIRE`](https://redis.io/docs/latest/commands/hexpire) and\n  [`HTTL`](https://redis.io/docs/latest/commands/httl) were added in Redis 7.4; the\n  demo relies on per-field TTL for the mixed-staleness story.\n* **Go 1.21 or later.**\n* The `go-redis` v9 client. The demo's `go.mod` pins\n  `github.com/redis/go-redis/v9 v9.18.0` or later.\n\nIf your Redis server is running elsewhere, start the demo with `--redis-addr`."
    },
    {
      "id": "running-the-demo",
      "title": "Running the demo",
      "role": "content",
      "text": ""
    },
    {
      "id": "get-the-source-files",
      "title": "Get the source files",
      "role": "content",
      "text": "The demo lives in a small Go module under\n[`feature-store/go`](https://github.com/redis/docs/tree/main/content/develop/use-cases/feature-store/go).\nClone the repo or copy the directory:\n\n[code example]"
    },
    {
      "id": "start-the-demo-server",
      "title": "Start the demo server",
      "role": "content",
      "text": "From the module directory:\n\n[code example]\n\nYou should see:\n\n[code example]\n\nBy default the demo wipes the configured key prefix on startup so each run\nstarts from a clean state. Pass `--no-reset` to keep any existing data, or\n`--key-prefix <prefix>` to point the demo at a different prefix entirely.\n\nOpen [http://127.0.0.1:8087](http://127.0.0.1:8087) in a browser. Useful\nthings to try:\n\n* Pick a user and click **Read features** with a mixed batch/streaming\n  subset — you'll see batch fields with no per-field TTL (covered by the\n  key-level TTL) and streaming fields with a positive per-field TTL.\n* Click **Pipeline HMGET** with `count=100` to see the latency of a\n  100-user batch read.\n* Click **Pause / resume** on the streaming worker and leave it paused for\n  ~5 minutes (or restart the server with `--streaming-ttl-seconds 30` to\n  make it visible in seconds). Re-run **Read features** on any user and\n  watch the streaming fields disappear while the batch fields stay.\n* Click **Inspect** on a user to see the full hash with field-level TTLs.\n* Click **Bulk-load** with a short TTL (say 30 seconds) and watch the user\n  count fall to zero on the next minute — the same thing that happens if a\n  daily batch run fails to land.\n* Click **Reset** to drop every user and start over.\n\nThe server is read/write against your local Redis. The default key prefix\nis `fs:user:`. Pass `--no-reset` to keep existing data across restarts, or\n`--redis-addr` to point at a different Redis."
    },
    {
      "id": "production-usage",
      "title": "Production usage",
      "role": "content",
      "text": "The guidance below focuses on the production concerns that are specific to\nrunning a feature store on Redis. For the generic go-redis production\nchecklist — connection-pool sizing, TLS, ACL, context cancellation, and\nretry policy — see the\n[go-redis production usage guide](https://redis.io/docs/latest/develop/clients/go/produsage)\nand the\n[connect-with-TLS recipe](https://redis.io/docs/latest/develop/clients/go/connect#connect-to-your-production-redis-with-tls).\nThe feature-store demo runs against `localhost` with the defaults; a real\ndeployment should harden the client first."
    },
    {
      "id": "plumb-the-right-context-to-each-call-site",
      "title": "Plumb the right context to each call site",
      "role": "content",
      "text": "go-redis takes a `context.Context` on every command, and the right context\ndepends on the call site:\n\n* **Inference handlers**: pass `r.Context()` (the request context) into the\n  store calls. If the client hangs up, the in-flight `HMGET` is cancelled\n  promptly and the connection is returned to the pool — important under\n  sustained load.\n* **Background workers**: pass a server-lifetime context (a\n  `context.Background()`-derived one stored on the worker struct, as\n  `StreamingWorker` does). A worker driven off `r.Context()` would die on\n  the very next tick after its triggering request completes.\n* **Batch jobs**: a `context.WithTimeout` is the usual choice so a stuck\n  Redis can't hold the materialization pipeline open indefinitely."
    },
    {
      "id": "pick-the-batch-ttl-to-outlast-a-failed-refresher",
      "title": "Pick the batch TTL to outlast a failed refresher",
      "role": "content",
      "text": "The whole-entity `EXPIRE` is your safety net against silent staleness from a\nbroken batch pipeline. Set it longer than your worst-case batch outage so a\nsingle missed run doesn't take the feature store offline, but short enough\nthat a sustained outage causes loud failures (missing entities) rather than\nquiet ones (yesterday's features being scored as today's). The standard\nchoice is one cycle of \"expected refresh interval × 2\" — for a daily batch,\n48 hours; for a 6-hour batch, 12 hours.\n\nThe same logic applies to the per-field streaming TTL: a few times the\nexpected update interval so a slow-but-alive streaming worker doesn't\nchurn features needlessly, but short enough that a stalled worker causes\nvisible freshness failures."
    },
    {
      "id": "co-locate-the-online-store-with-serving-not-with-training",
      "title": "Co-locate the online store with serving, not with training",
      "role": "content",
      "text": "The online store's hash representation does *not* have to match the schema\nin your offline store. The batch materialization step is your chance to\nflatten joins, encode categoricals, and project to whatever shape the model\nserver wants — so the request path is exactly one `HMGET` and zero\ntransforms.\n\nThe training pipeline reads from the offline store with its own schema; the\nserving pipeline reads from Redis with the flattened serving schema.\nKeeping those two pipelines as the same code path is what prevents\ntraining-serving skew."
    },
    {
      "id": "pipeline-batch-reads-across-shards",
      "title": "Pipeline batch reads across shards",
      "role": "content",
      "text": "On a single Redis instance, pipelining `HMGET` across `N` users through\n`Pipeline.Exec` is one round trip. A Redis Cluster is different: a single\n`Pipeline.Exec` is bound to one shard, because non-cross-slot pipelines can\nonly target one node, and the keys for a typical user batch will land on\nmultiple shards. For batch reads on a cluster, use the\n[`ClusterClient`](https://redis.io/docs/latest/develop/clients/go/connect) — its\n`Pipeline` knows how to bucket commands per-shard and ship one batch per\nshard in parallel. For a small number of frequently-queried users (a\ntop-N customer list, for example), a hash tag like `fs:user:{vip}:u0001`\nforces a known set of keys onto the same shard so one pipeline can cover\nall of them in a single round trip."
    },
    {
      "id": "make-hexpire-part-of-every-streaming-write",
      "title": "Make HEXPIRE part of every streaming write",
      "role": "content",
      "text": "The single biggest correctness lever in this design is that the streaming\nwrite applies `HEXPIRE` *every time*. If a streaming worker writes a field\nwithout renewing its TTL, the field carries whatever expiry was there\nbefore — possibly none, possibly stale — and the mixed-staleness invariant\nbreaks. Keep the `HSET` and `HEXPIRE` in the same pipeline (or, even safer,\nin the same [Lua script](https://redis.io/docs/latest/develop/programmability/eval-intro)\nif you don't trust the call site)."
    },
    {
      "id": "avoid-hgetall-on-the-request-path",
      "title": "Avoid HGETALL on the request path",
      "role": "content",
      "text": "`HGETALL` reads every field on the hash, including ones the model doesn't\nneed. With dozens of features per entity, that is wasted serialization work\non the server and wasted bandwidth on the wire. Always specify the field\nlist explicitly with `HMGet` in the model server.\n\nThe exception is debugging and feature-set discovery, where you genuinely\nwant the full hash. The demo's \"Inspect\" button uses `HGetAll` for exactly\nthis reason."
    },
    {
      "id": "inspect-the-store-directly-with-redis-cli",
      "title": "Inspect the store directly with redis-cli",
      "role": "content",
      "text": "When testing or troubleshooting, the cli tells you everything:\n\n[code example]\n\nA streaming field that returns `-2` from `HTTL` doesn't exist on the hash\n(either it was never written, or it expired); `-1` means the field has no\nTTL set (and is therefore covered only by the key-level `EXPIRE`); any\npositive value is the remaining TTL in seconds."
    },
    {
      "id": "learn-more",
      "title": "Learn more",
      "role": "related",
      "text": "This example uses the following Redis commands:\n\n* [`HSET`](https://redis.io/docs/latest/commands/hset) to write a feature or a whole\n  feature row in one call.\n* [`HMGET`](https://redis.io/docs/latest/commands/hmget) to retrieve any subset of\n  features for one entity in one round trip.\n* [`HGETALL`](https://redis.io/docs/latest/commands/hgetall) for debugging and\n  feature-set discovery.\n* [`HEXPIRE`](https://redis.io/docs/latest/commands/hexpire) and\n  [`HTTL`](https://redis.io/docs/latest/commands/httl) for per-field TTL on streaming\n  features (Redis 7.4+).\n* [`EXPIRE`](https://redis.io/docs/latest/commands/expire) and\n  [`TTL`](https://redis.io/docs/latest/commands/ttl) for the whole-entity TTL aligned\n  with the batch materialization cycle.\n* Pipelined `HMGET` across many entities for batch scoring with one network\n  round trip — see\n  [transactions and pipelining](https://redis.io/docs/latest/develop/clients/go/transpipe).\n\nSee the [go-redis documentation](https://redis.io/docs/latest/develop/clients/go) for\nthe full client reference, and the\n[Hashes overview](https://redis.io/docs/latest/develop/data-types/hashes) for the deeper\nconceptual model — including the listpack encoding that makes small hashes\nparticularly compact in memory, which matters at feature-store scale."
    }
  ],
  "examples": [
    {
      "id": "the-feature-store-helper-ex0",
      "language": "go",
      "code": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/redis/go-redis/v9\"\n\tfs \"featurestore\"\n)\n\nfunc main() {\n\tctx := context.Background()\n\trdb := redis.NewClient(&redis.Options{Addr: \"localhost:6379\"})\n\tdefer rdb.Close()\n\n\tstore := fs.NewFeatureStore(rdb,\n\t\t\"fs:user:\",\n\t\t24*time.Hour,   // whole-entity TTL aligned with the daily batch cycle\n\t\t5*time.Minute,  // per-field TTL on each streaming feature\n\t)\n\n\t// Batch materialization: one HSET + EXPIRE per user, all pipelined.\n\trows := map[string]fs.FeatureMap{\n\t\t\"u0001\": {\"country_iso\": \"US\", \"risk_segment\": \"low\",\n\t\t\t\"tx_count_7d\": 14, \"avg_amount_30d\": 92.40,\n\t\t\t\"account_age_days\": 612, \"chargeback_count_180d\": 0},\n\t\t\"u0002\": {\"country_iso\": \"GB\", \"risk_segment\": \"medium\",\n\t\t\t\"tx_count_7d\": 47, \"avg_amount_30d\": 220.10,\n\t\t\t\"account_age_days\": 1840, \"chargeback_count_180d\": 1},\n\t}\n\tstore.BulkLoad(ctx, rows, store.BatchTTL)\n\n\t// Streaming write: HSET + HEXPIRE on just the fields that changed.\n\tstore.UpdateStreaming(ctx, \"u0001\", fs.FeatureMap{\n\t\t\"last_login_ts\":     time.Now().UnixMilli(),\n\t\t\"last_device_id\":    \"ios-9f02\",\n\t\t\"tx_count_5m\":       3,\n\t\t\"failed_logins_15m\": 0,\n\t\t\"session_country\":   \"US\",\n\t}, store.StreamingTTL)\n\n\t// Inference read: HMGET of whatever the model needs.\n\tfeatures, _ := store.GetFeatures(ctx, \"u0001\", []string{\n\t\t\"risk_segment\", \"tx_count_7d\", \"avg_amount_30d\",\n\t\t\"tx_count_5m\", \"failed_logins_15m\",\n\t})\n\tfmt.Println(features)\n\n\t// Batch scoring: pipelined HMGET across many users.\n\tbatch, _ := store.BatchGetFeatures(ctx,\n\t\t[]string{\"u0001\", \"u0002\", \"u0003\"},\n\t\t[]string{\"risk_segment\", \"tx_count_5m\", \"failed_logins_15m\"},\n\t)\n\tfmt.Println(batch)\n}",
      "section_id": "the-feature-store-helper"
    },
    {
      "id": "package-layout-ex0",
      "language": "text",
      "code": "feature-store/go/\n├── go.mod\n├── feature_store.go       (package featurestore)\n├── build_features.go      (package featurestore; SynthesizeUsers + CLI)\n├── streaming_worker.go    (package featurestore)\n├── demo_server.go         (package featurestore; RunDemoServer)\n└── cmd/\n    ├── build_features/main.go   (package main, shim → fs.BuildFeaturesCLI)\n    └── demo_server/main.go      (package main, shim → fs.RunDemoServer)",
      "section_id": "package-layout"
    },
    {
      "id": "data-model-ex0",
      "language": "text",
      "code": "fs:user:u0001                                   TTL = 86400 s (key-level)\n  country_iso=US                                <no field TTL>\n  risk_segment=low                              <no field TTL>\n  account_age_days=612                          <no field TTL>\n  tx_count_7d=14                                <no field TTL>\n  avg_amount_30d=92.40                          <no field TTL>\n  chargeback_count_180d=0                       <no field TTL>\n  last_login_ts=1716998413541                   TTL = 300 s (per field, HEXPIRE)\n  last_device_id=ios-9f02                       TTL = 300 s (per field, HEXPIRE)\n  tx_count_5m=3                                 TTL = 300 s (per field, HEXPIRE)\n  failed_logins_15m=0                           TTL = 300 s (per field, HEXPIRE)\n  session_country=US                            TTL = 300 s (per field, HEXPIRE)",
      "section_id": "data-model"
    },
    {
      "id": "bulk-loading-batch-features-ex0",
      "language": "go",
      "code": "func (fs *FeatureStore) BulkLoad(ctx context.Context, rows map[string]FeatureMap, ttl time.Duration) (int, error) {\n    if ttl == 0 {\n        ttl = fs.BatchTTL\n    }\n    if len(rows) == 0 {\n        return 0, nil\n    }\n    pipe := fs.rdb.Pipeline()\n    for entityID, fields := range rows {\n        key := fs.KeyFor(entityID)\n        encoded := make(map[string]any, len(fields))\n        for name, value := range fields {\n            encoded[name] = encode(value)\n        }\n        pipe.HSet(ctx, key, encoded)\n        pipe.Expire(ctx, key, ttl)\n    }\n    if _, err := pipe.Exec(ctx); err != nil {\n        return 0, fmt.Errorf(\"bulk load: %w\", err)\n    }\n    ...\n}",
      "section_id": "bulk-loading-batch-features"
    },
    {
      "id": "streaming-writes-with-per-field-ttl-ex0",
      "language": "go",
      "code": "func (fs *FeatureStore) UpdateStreaming(ctx context.Context, entityID string, fields FeatureMap, ttl time.Duration) error {\n    if len(fields) == 0 {\n        return nil\n    }\n    if ttl == 0 {\n        ttl = fs.StreamingTTL\n    }\n    key := fs.KeyFor(entityID)\n    encoded := make(map[string]any, len(fields))\n    names := make([]string, 0, len(fields))\n    for name, value := range fields {\n        encoded[name] = encode(value)\n        names = append(names, name)\n    }\n    pipe := fs.rdb.Pipeline()\n    pipe.HSet(ctx, key, encoded)\n    hexpireCmd := pipe.HExpire(ctx, key, ttl, names...)\n    if _, err := pipe.Exec(ctx); err != nil {\n        return fmt.Errorf(\"update streaming: %w\", err)\n    }\n    codes, _ := hexpireCmd.Result()\n    for _, code := range codes {\n        if code != 1 {\n            return fmt.Errorf(\"HEXPIRE did not set every field TTL for %s: %v\", key, codes)\n        }\n    }\n    ...\n}",
      "section_id": "streaming-writes-with-per-field-ttl"
    },
    {
      "id": "inference-reads-with-hmget-ex0",
      "language": "go",
      "code": "func (fs *FeatureStore) GetFeatures(ctx context.Context, entityID string, fieldNames []string) (map[string]string, error) {\n    key := fs.KeyFor(entityID)\n    if fieldNames == nil {\n        return fs.rdb.HGetAll(ctx, key).Result()\n    }\n    if len(fieldNames) == 0 {\n        return map[string]string{}, nil\n    }\n    values, err := fs.rdb.HMGet(ctx, key, fieldNames...).Result()\n    if err != nil {\n        return nil, err\n    }\n    out := make(map[string]string, len(fieldNames))\n    for i, name := range fieldNames {\n        if s, ok := values[i].(string); ok {\n            out[name] = s\n        }\n    }\n    return out, nil\n}",
      "section_id": "inference-reads-with-hmget"
    },
    {
      "id": "batch-scoring-with-pipelined-hmget-ex0",
      "language": "go",
      "code": "func (fs *FeatureStore) BatchGetFeatures(ctx context.Context, entityIDs, fieldNames []string) (map[string]map[string]string, error) {\n    if len(entityIDs) == 0 || len(fieldNames) == 0 {\n        return map[string]map[string]string{}, nil\n    }\n    pipe := fs.rdb.Pipeline()\n    cmds := make([]*redis.SliceCmd, len(entityIDs))\n    for i, id := range entityIDs {\n        cmds[i] = pipe.HMGet(ctx, fs.KeyFor(id), fieldNames...)\n    }\n    if _, err := pipe.Exec(ctx); err != nil && !errors.Is(err, redis.Nil) {\n        return nil, err\n    }\n    out := make(map[string]map[string]string, len(entityIDs))\n    for i, id := range entityIDs {\n        values, _ := cmds[i].Result()\n        row := make(map[string]string, len(fieldNames))\n        for j, name := range fieldNames {\n            if s, ok := values[j].(string); ok {\n                row[name] = s\n            }\n        }\n        out[id] = row\n    }\n    return out, nil\n}",
      "section_id": "batch-scoring-with-pipelined-hmget"
    },
    {
      "id": "the-streaming-worker-ex0",
      "language": "go",
      "code": "func (w *StreamingWorker) doTick(ctx context.Context) error {\n    ids, err := w.store.ListEntityIDs(ctx, 500)\n    if err != nil {\n        return err\n    }\n    if len(ids) == 0 {\n        return nil\n    }\n    n := w.usersPerTick\n    if n > len(ids) {\n        n = len(ids)\n    }\n    chosen := w.rng.Perm(len(ids))[:n]\n    nowMs := time.Now().UnixMilli()\n    for _, idx := range chosen {\n        fields := FeatureMap{\n            \"last_login_ts\":     nowMs,\n            \"last_device_id\":    w.choice(deviceIDs),\n            \"tx_count_5m\":       w.intn(13),\n            \"failed_logins_15m\": w.weightedInt(failedLoginBuckets, failedLoginWeights),\n            \"session_country\":   w.choice(sessionCountries),\n        }\n        if err := w.store.UpdateStreaming(ctx, ids[idx], fields, 0); err != nil {\n            return err\n        }\n    }\n    return nil\n}",
      "section_id": "the-streaming-worker"
    },
    {
      "id": "the-batch-builder-ex0",
      "language": "go",
      "code": "func SynthesizeUsers(count int, seed int64) map[string]FeatureMap {\n    rng := rand.New(rand.NewSource(seed))\n    users := make(map[string]FeatureMap, count)\n    for i := 1; i <= count; i++ {\n        uid := fmt.Sprintf(\"u%04d\", i)\n        users[uid] = FeatureMap{\n            \"country_iso\":           countryChoices[rng.Intn(len(countryChoices))],\n            \"risk_segment\":          weightedChoiceString(rng, riskSegments, riskWeights),\n            \"account_age_days\":      rng.Intn(2400-7+1) + 7,\n            \"tx_count_7d\":           rng.Intn(81),\n            \"avg_amount_30d\":        roundTo2(rng.Float64()*345.0 + 5.0),\n            \"chargeback_count_180d\": weightedChoiceInt(rng, chargebackBuckets, chargebackWeights),\n        }\n    }\n    return users\n}",
      "section_id": "the-batch-builder"
    },
    {
      "id": "the-batch-builder-ex1",
      "language": "bash",
      "code": "go run ./cmd/build_features --count 500 --ttl-seconds 3600",
      "section_id": "the-batch-builder"
    },
    {
      "id": "get-the-source-files-ex0",
      "language": "bash",
      "code": "git clone https://github.com/redis/docs.git\ncd docs/content/develop/use-cases/feature-store/go\ngo mod tidy",
      "section_id": "get-the-source-files"
    },
    {
      "id": "start-the-demo-server-ex0",
      "language": "bash",
      "code": "go run ./cmd/demo_server",
      "section_id": "start-the-demo-server"
    },
    {
      "id": "start-the-demo-server-ex1",
      "language": "text",
      "code": "Dropping any existing users under 'fs:user:*' for a clean demo run (pass --no-reset to keep them).\nRedis feature-store demo server listening on http://127.0.0.1:8087\nUsing Redis at localhost:6379 with key prefix 'fs:user:' (batch TTL 86400s, streaming TTL 300s)\nMaterialized 200 user(s); streaming worker running.",
      "section_id": "start-the-demo-server"
    },
    {
      "id": "inspect-the-store-directly-with-redis-cli-ex0",
      "language": "bash",
      "code": "# How many users currently in the store\nredis-cli --scan --pattern 'fs:user:*' | wc -l\n\n# One user's full hash and key-level TTL\nredis-cli HGETALL fs:user:u0001\nredis-cli TTL    fs:user:u0001\n\n# Per-field TTL on the streaming fields\nredis-cli HTTL fs:user:u0001 FIELDS 5 \\\n  last_login_ts last_device_id tx_count_5m failed_logins_15m session_country\n\n# Sample HMGET as the model would issue it\nredis-cli HMGET fs:user:u0001 risk_segment tx_count_7d avg_amount_30d tx_count_5m",
      "section_id": "inspect-the-store-directly-with-redis-cli"
    }
  ]
}
