{
  "id": "java-jedis",
  "title": "Redis feature store with Jedis",
  "url": "https://redis.io/docs/latest/develop/use-cases/feature-store/java-jedis/",
  "summary": "Build a Redis-backed online feature store in Java with Jedis",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-06-04T14:49:57+01:00",
  "children": [],
  "page_type": "content",
  "content_hash": "547ca1bf4966c3b1e689c64721c787c7a2c957a6e49752471f947e28f086271a",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This guide shows you how to build a small Redis-backed online feature store in\nJava with [Jedis](https://redis.io/docs/latest/develop/clients/jedis). It includes a\nlocal web server built with the JDK's `com.sun.net.httpserver.HttpServer` so\nyou can bulk-load a batch of users with a key-level TTL, run a streaming\nworker that overwrites real-time features with per-field TTL, retrieve any\nsubset of features for one user under 2 ms, and pipeline `HMGET` across a\nhundred users for 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`BuildFeatures.java` — 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`StreamingWorker.java` — 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 `FeatureStore.java`'s helper class.\n\nThat gives you:\n\n* A single round trip for retrieval — any subset of features for one entity\n  in 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 `BuildFeatures.synthesizeUsers(N, seed)` (in\n   production, the equivalent computation lives in an offline pipeline against\n   the warehouse). The result is `Map<String, Map<String, Object>>` keyed by\n   user ID.\n2. `store.bulkLoad(rows, ttlSeconds)` queues one\n   [`HSET`](https://redis.io/docs/latest/commands/hset) plus one\n   [`EXPIRE`](https://redis.io/docs/latest/commands/expire) per user through Jedis's\n   [`Pipeline`](https://redis.io/docs/latest/develop/clients/jedis/transpipe), then\n   `pipe.sync()` ships the whole batch in a single round trip. The `HSET`\n   writes every batch field; the `EXPIRE` is what makes the entity disappear\n   if the next batch run fails, so inference reads a missing entity rather\n   than silently outdated 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(userId, fields, ttlSeconds)`. 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(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 `null` for any field that\n   doesn't exist (or has expired).\n3. For batch inference, the model server calls\n   `store.batchGetFeatures(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 via Jedis's `Pipeline.sync()`."
    },
    {
      "id": "the-feature-store-helper",
      "title": "The feature-store helper",
      "role": "content",
      "text": "The `FeatureStore` class wraps the read/write paths\n([source](https://github.com/redis/docs/blob/main/content/develop/use-cases/feature-store/java-jedis/FeatureStore.java)):\n\n[code example]"
    },
    {
      "id": "project-layout",
      "title": "Project layout",
      "role": "content",
      "text": "The four `.java` files and the `pom.xml` live in the same directory — the\n`build-helper-maven-plugin` adds the project root as the source directory so\nthe Java sources sit alongside the build descriptor. Run with:\n\n[code example]"
    },
    {
      "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\"` (`encodeValue(Object)` in `FeatureStore.java`) and renders\neverything else with `Object.toString()`. The model server is responsible for\nparsing 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` queues one `HSET` and one `EXPIRE` per user into a single\n`Pipeline` and calls `sync()` to ship the lot. With 500 users that's 1000\ncommands in one network call — Redis processes them sequentially on the\nserver side but the client only pays one RTT.\n\n[code example]\n\nJedis's `pipelined()` 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'd wrap each user in a `Transaction` or a\n[Lua script](https://redis.io/docs/latest/develop/programmability/eval-intro); for a\ndaily 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 queued in one\n`Pipeline` and Redis runs them in order: the `HSET` first creates or\noverwrites the fields, then `HEXPIRE` attaches a TTL to each of those same\nfields. `HEXPIRE` returns one status code per field — `1` if the TTL was\nset, `2` if the expiry was 0 or in the past (so Redis deleted the field\ninstead), `0` if an `NX | XX | GT | LT` conditional flag was set and not met\n(we never use one here), `-2` if the field doesn't exist on the key. The\nhelper throws if any code is anything other than `1`, so the \"every\nstreaming write renews its TTL\" invariant fails loudly rather than silently\nleaving a streaming field with no expiry attached.\n\n`Response<List<Long>>` is Jedis's deferred-result wrapper for pipelined\ncommands: queue the command, call `pipe.sync()` to ship the batch, then read\neach result via `.get()`. The `Response` for `hexpire` returns the per-field\ncodes; that list is what the helper validates above.\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. Jedis 5.2\n> was the first release with the bindings; the demo's `pom.xml` pins 6.2.\n> On older Redis builds you would have to put streaming features on their\n> own keys (one key per feature, or one key per feature group) and set a\n> key-level `EXPIRE` instead — at the cost of giving up the single-`HMGET`\n> 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 `null` in the `List<String>` Jedis returns. 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 30 users in\n~1 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: a single `Pipeline.sync()` is bound to one\nshard, because cross-slot pipelines on a cluster connection don't make sense.\nFor batch reads on a cluster, use\n[`JedisCluster`](https://redis.io/docs/latest/develop/clients/jedis) and either fan out\nparallel `hmget` calls (the cluster client routes per-shard for you) or, for\ntighter control, group the IDs by hash slot ahead of time and issue one\n`Pipeline.sync()` against each shard's connection in parallel. A hash tag\nlike `fs:user:{vip}:u0001` forces a known set of keys onto the same shard so\none pipeline can cover all of them in a single round trip."
    },
    {
      "id": "the-streaming-worker",
      "title": "The streaming worker",
      "role": "content",
      "text": "`StreamingWorker.java` 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/java-jedis/StreamingWorker.java)).\nIt runs as a daemon `Thread` next to the demo server so the UI can start,\npause, and resume it; in production this code would live in the streaming\nlayer.\n\nEvery tick the worker picks a few random users, generates a new value for\neach streaming feature, and calls `store.updateStreaming(userId, fields)`.\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 `streamingTtlSeconds` and the streaming fields\ndisappear from every user's hash one by one, while the batch fields remain\nunder the longer key-level `EXPIRE`. The demo's `Pause / resume` button lets\nyou see this happen in real time.\n\n`pause()` only blocks *future* ticks from running — the thread checks the\nflag at the top of the loop and skips its turn. A reset that's about to\n`DEL` every key needs to wait out an already-running tick too, which is\nwhat `waitForIdle()` is for: the demo's `Reset` handler calls\n`worker.pause()` *and* `worker.waitForIdle()` before it issues the `DEL`\nsweep, so a mid-flight tick can't recreate a user under a streaming-only\nhash with no key-level TTL."
    },
    {
      "id": "the-batch-builder",
      "title": "The batch builder",
      "role": "content",
      "text": "`BuildFeatures.java` is the demo's nightly materializer\n([source](https://github.com/redis/docs/blob/main/content/develop/use-cases/feature-store/java-jedis/BuildFeatures.java)).\nIt generates synthetic feature rows and calls `store.bulkLoad` once. The\nsynthesis itself is not the point — in a real deployment the equivalent code\nreads from the offline store (Snowflake, BigQuery, Iceberg) and writes the\nresulting 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": "`DemoServer.java` runs the JDK `HttpServer` on port 8088 with a fixed thread\npool. The HTML page lets you:\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, plus a `JedisPool` that all handlers borrow\nconnections from. 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* **Java 17 or later.** The demo uses switch expressions with arrow\n  labels (`case \"...\" -> ...`), records, and text blocks.\n* **Jedis 5.2 or later.** The demo's `pom.xml` pins\n  `redis.clients:jedis:6.2.0`. Field-level TTL bindings (`hexpire`, `httl`,\n  `hpersist`) ship from Jedis 5.2.\n\nIf your Redis server is running elsewhere, start the demo with `--redis-host`\nand `--redis-port`."
    },
    {
      "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 Maven project under\n[`feature-store/java-jedis`](https://github.com/redis/docs/tree/main/content/develop/use-cases/feature-store/java-jedis).\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 project 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.\nMaven exec passes CLI args via `-Dexec.args`:\n\n[code example]\n\nOpen [http://127.0.0.1:8088](http://127.0.0.1:8088) 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-host` / `--redis-port` 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 Jedis production checklist\n— `JedisPool` sizing, AUTH/ACL, retry policy, sentinel/cluster failover —\nsee the\n[Jedis production usage guide](https://redis.io/docs/latest/develop/clients/jedis/produsage).\nFor TLS specifically, follow the\n[connect-with-TLS recipe](https://redis.io/docs/latest/develop/clients/jedis/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": "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 churn\nfeatures needlessly, but short enough that a stalled worker causes visible\nfreshness 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, `Pipeline.sync()` across `N` `hmget` calls is\none round trip. A Redis Cluster is different: a single `Pipeline.sync()` is\nbound to one shard, because cross-slot pipelines on a cluster connection\ndon't make sense, and the keys for a typical user batch will land on\nmultiple shards. For batch reads on a cluster, use\n[`JedisCluster`](https://redis.io/docs/latest/develop/clients/jedis) — its\nimplementation routes per-shard for you. For tighter control, group the IDs\nby hash slot ahead of time and issue one `Pipeline.sync()` per shard's\nconnection 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 before\n— possibly none, possibly stale — and the mixed-staleness invariant breaks.\nKeep the `HSET` and `HEXPIRE` in the same pipeline (or, even safer, in the\nsame [Lua script](https://redis.io/docs/latest/develop/programmability/eval-intro) if\nyou 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": "size-the-jedispool-for-the-request-shape",
      "title": "Size the JedisPool for the request shape",
      "role": "content",
      "text": "Every `FeatureStore` helper method borrows a connection from the\n`JedisPool` for the duration of one Redis call (or one `Pipeline.sync()`)\nand returns it via the try-with-resources block. One HTTP handler can\ntherefore borrow several connections sequentially — `/read`, for example,\nmakes one `hmget` call, one `httl` call, and one `ttl` call, each of\nwhich is its own borrow.\n\nThe demo uses `maxTotal=64`. In production, size `maxTotal` to comfortably\nexceed your peak concurrent borrow count: that's roughly\n`(concurrent HTTP handlers × Redis calls per handler in flight at once) +\n(background worker borrow rate)`. Setting it too low forces some borrows\nto block waiting for a returned connection — a slow read-side cliff that\ndoesn't show up under load tests with very few clients."
    },
    {
      "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/jedis/transpipe).\n\nSee the [Jedis documentation](https://redis.io/docs/latest/develop/clients/jedis) 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": "java",
      "code": "import redis.clients.jedis.JedisPool;\nimport redis.clients.jedis.JedisPoolConfig;\n\nJedisPoolConfig cfg = new JedisPoolConfig();\ncfg.setMaxTotal(64);\nJedisPool pool = new JedisPool(cfg, \"localhost\", 6379);\nFeatureStore store = new FeatureStore(pool,\n    \"fs:user:\",\n    24L * 60L * 60L,    // whole-entity TTL aligned with the daily batch cycle\n    5L * 60L            // per-field TTL on each streaming feature\n);\n\n// Batch materialization: one HSET + EXPIRE per user, all pipelined.\nMap<String, Map<String, Object>> rows = Map.of(\n    \"u0001\", Map.of(\n        \"country_iso\", \"US\", \"risk_segment\", \"low\",\n        \"tx_count_7d\", 14, \"avg_amount_30d\", 92.40,\n        \"account_age_days\", 612, \"chargeback_count_180d\", 0),\n    \"u0002\", Map.of(\n        \"country_iso\", \"GB\", \"risk_segment\", \"medium\",\n        \"tx_count_7d\", 47, \"avg_amount_30d\", 220.10,\n        \"account_age_days\", 1840, \"chargeback_count_180d\", 1));\nstore.bulkLoad(rows);\n\n// Streaming write: HSET + HEXPIRE on just the fields that changed.\nstore.updateStreaming(\"u0001\", Map.of(\n    \"last_login_ts\", System.currentTimeMillis(),\n    \"last_device_id\", \"ios-9f02\",\n    \"tx_count_5m\", 3,\n    \"failed_logins_15m\", 0,\n    \"session_country\", \"US\"));\n\n// Inference read: HMGET of whatever the model needs.\nMap<String, String> features = store.getFeatures(\"u0001\", List.of(\n    \"risk_segment\", \"tx_count_7d\", \"avg_amount_30d\",\n    \"tx_count_5m\", \"failed_logins_15m\"));\n\n// Batch scoring: pipelined HMGET across many users.\nMap<String, Map<String, String>> batch = store.batchGetFeatures(\n    List.of(\"u0001\", \"u0002\", \"u0003\"),\n    List.of(\"risk_segment\", \"tx_count_5m\", \"failed_logins_15m\"));",
      "section_id": "the-feature-store-helper"
    },
    {
      "id": "project-layout-ex0",
      "language": "bash",
      "code": "mvn package\nmvn exec:java -Dexec.mainClass=DemoServer",
      "section_id": "project-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": "java",
      "code": "public int bulkLoad(Map<String, Map<String, Object>> rows, long ttlSeconds) {\n    if (rows.isEmpty()) return 0;\n    try (Jedis jedis = pool.getResource()) {\n        Pipeline pipe = jedis.pipelined();\n        for (Map.Entry<String, Map<String, Object>> e : rows.entrySet()) {\n            String key = keyFor(e.getKey());\n            Map<String, String> encoded = encode(e.getValue());\n            pipe.hset(key, encoded);\n            pipe.expire(key, ttlSeconds);\n        }\n        pipe.sync();\n    }\n    ...\n}",
      "section_id": "bulk-loading-batch-features"
    },
    {
      "id": "streaming-writes-with-per-field-ttl-ex0",
      "language": "java",
      "code": "public void updateStreaming(String entityId, Map<String, Object> fields, long ttlSeconds) {\n    if (fields.isEmpty()) return;\n    String key = keyFor(entityId);\n    Map<String, String> encoded = encode(fields);\n    String[] names = encoded.keySet().toArray(new String[0]);\n\n    List<Long> expireCodes;\n    try (Jedis jedis = pool.getResource()) {\n        Pipeline pipe = jedis.pipelined();\n        pipe.hset(key, encoded);\n        Response<List<Long>> expireResp = pipe.hexpire(key, ttlSeconds, names);\n        pipe.sync();\n        expireCodes = expireResp.get();\n    }\n    for (Long code : expireCodes) {\n        if (code == null || code != 1L) {\n            throw new IllegalStateException(\n                \"HEXPIRE did not set every field TTL for \" + key + \": \" + expireCodes);\n        }\n    }\n    ...\n}",
      "section_id": "streaming-writes-with-per-field-ttl"
    },
    {
      "id": "inference-reads-with-hmget-ex0",
      "language": "java",
      "code": "public Map<String, String> getFeatures(String entityId, List<String> fieldNames) {\n    String key = keyFor(entityId);\n    Map<String, String> out = new LinkedHashMap<>();\n    if (fieldNames == null) {\n        try (Jedis jedis = pool.getResource()) {\n            Map<String, String> all = jedis.hgetAll(key);\n            if (all != null) out.putAll(all);\n        }\n        return out;\n    }\n    if (fieldNames.isEmpty()) return out;\n    List<String> values;\n    try (Jedis jedis = pool.getResource()) {\n        values = jedis.hmget(key, fieldNames.toArray(new String[0]));\n    }\n    for (int i = 0; i < fieldNames.size(); i++) {\n        String v = values.get(i);\n        if (v != null) out.put(fieldNames.get(i), v);\n    }\n    return out;\n}",
      "section_id": "inference-reads-with-hmget"
    },
    {
      "id": "batch-scoring-with-pipelined-hmget-ex0",
      "language": "java",
      "code": "public Map<String, Map<String, String>> batchGetFeatures(\n        List<String> entityIds, List<String> fieldNames) {\n    if (entityIds.isEmpty() || fieldNames.isEmpty()) {\n        return Collections.emptyMap();\n    }\n    String[] names = fieldNames.toArray(new String[0]);\n    List<Response<List<String>>> responses = new ArrayList<>(entityIds.size());\n    try (Jedis jedis = pool.getResource()) {\n        Pipeline pipe = jedis.pipelined();\n        for (String id : entityIds) {\n            responses.add(pipe.hmget(keyFor(id), names));\n        }\n        pipe.sync();\n    }\n    Map<String, Map<String, String>> out = new LinkedHashMap<>();\n    for (int i = 0; i < entityIds.size(); i++) {\n        List<String> values = responses.get(i).get();\n        Map<String, String> row = new LinkedHashMap<>();\n        for (int j = 0; j < fieldNames.size(); j++) {\n            String v = values.get(j);\n            if (v != null) row.put(fieldNames.get(j), v);\n        }\n        out.put(entityIds.get(i), row);\n    }\n    return out;\n}",
      "section_id": "batch-scoring-with-pipelined-hmget"
    },
    {
      "id": "the-streaming-worker-ex0",
      "language": "java",
      "code": "private void doTick() {\n    List<String> ids = store.listEntityIds(500);\n    if (ids.isEmpty()) return;\n    List<String> picks = sample(ids, usersPerTick);\n    long nowMs = System.currentTimeMillis();\n    for (String id : picks) {\n        Map<String, Object> fields = new LinkedHashMap<>();\n        fields.put(\"last_login_ts\", nowMs);\n        fields.put(\"last_device_id\", choice(DEVICE_IDS));\n        fields.put(\"tx_count_5m\", intn(13));\n        fields.put(\"failed_logins_15m\", weightedInt(FAILED_LOGIN_BUCKETS, FAILED_LOGIN_WEIGHTS));\n        fields.put(\"session_country\", choice(SESSION_COUNTRIES));\n        store.updateStreaming(id, fields);\n    }\n    ...\n}",
      "section_id": "the-streaming-worker"
    },
    {
      "id": "the-batch-builder-ex0",
      "language": "java",
      "code": "public static Map<String, Map<String, Object>> synthesizeUsers(int count, long seed) {\n    Random rng = new Random(seed);\n    Map<String, Map<String, Object>> users = new LinkedHashMap<>(count);\n    for (int i = 1; i <= count; i++) {\n        String uid = String.format(\"u%04d\", i);\n        Map<String, Object> row = new LinkedHashMap<>();\n        row.put(\"country_iso\", COUNTRY_CHOICES.get(rng.nextInt(COUNTRY_CHOICES.size())));\n        row.put(\"risk_segment\", weightedChoice(rng, RISK_SEGMENTS, RISK_WEIGHTS));\n        row.put(\"account_age_days\", 7 + rng.nextInt(2394));\n        row.put(\"tx_count_7d\", rng.nextInt(81));\n        row.put(\"avg_amount_30d\", Math.round((5.0 + rng.nextDouble() * 345.0) * 100.0) / 100.0);\n        row.put(\"chargeback_count_180d\", weightedChoiceInt(rng, CHARGEBACK_BUCKETS, CHARGEBACK_WEIGHTS));\n        users.put(uid, row);\n    }\n    return users;\n}",
      "section_id": "the-batch-builder"
    },
    {
      "id": "the-batch-builder-ex1",
      "language": "bash",
      "code": "mvn exec:java -Dexec.mainClass=BuildFeatures -Dexec.args=\"--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/java-jedis\nmvn package",
      "section_id": "get-the-source-files"
    },
    {
      "id": "start-the-demo-server-ex0",
      "language": "bash",
      "code": "mvn exec:java -Dexec.mainClass=DemoServer",
      "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:8088\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": "start-the-demo-server-ex2",
      "language": "bash",
      "code": "mvn exec:java -Dexec.mainClass=DemoServer \\\n    -Dexec.args=\"--port 9000 --streaming-ttl-seconds 30\"",
      "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"
    }
  ]
}
