{
  "id": "ruby",
  "title": "Redis session store with Ruby",
  "url": "https://redis.io/docs/latest/develop/use-cases/session-store/ruby/",
  "summary": "Implement a Redis-backed session store in Ruby with redis-rb",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-04-16T13:29:55-07:00",
  "children": [],
  "page_type": "content",
  "content_hash": "5bdcc969f272185cb45b79d3dfcc70b54cb3ccb42491246b51f50a3a3d6c821e",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This guide shows you how to implement a Redis-backed session store in Ruby with [`redis-rb`](https://redis.io/docs/latest/develop/clients/ruby). It includes a small local web server built with WEBrick so you can see the session lifecycle end to end."
    },
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Session storage is a common Redis use case for web applications. Instead of keeping session state in local process memory, you store it in Redis and send the browser only an opaque session ID in a cookie.\n\nThat gives you:\n\n* Shared sessions across multiple app servers\n* Automatic expiration using Redis TTLs\n* Fast reads and updates for small pieces of per-user state\n* A clean separation between browser cookies and server-side session data\n\nIn this example, each session is stored as a Redis hash with a key like `session:{session_id}`. The hash holds lightweight fields such as the username, page view count, timestamps, and the configured session TTL. The key also has an expiration so inactive sessions are removed automatically."
    },
    {
      "id": "how-it-works",
      "title": "How it works",
      "role": "content",
      "text": "The flow looks like this:\n\n1. A user submits a login form\n2. The server generates a random session ID with Ruby's `SecureRandom`\n3. The server stores session data in Redis under `session:{id}`\n4. The server sends a `sid` cookie containing only the session ID\n5. Later requests read the cookie, load the hash from Redis, and refresh the TTL\n6. Logging out deletes the Redis key and clears the cookie\n\nBecause the cookie only contains an opaque identifier, the browser never receives the actual session data. That stays in Redis."
    },
    {
      "id": "the-ruby-session-store",
      "title": "The Ruby session store",
      "role": "content",
      "text": "The `RedisSessionStore` class wraps the basic session operations\n([source](session_store.rb)):\n\n[code example]\n\nRuby's keyword arguments make the constructor options readable, and the store returns hashes and scalars that fit naturally with typical Ruby application code."
    },
    {
      "id": "data-model",
      "title": "Data model",
      "role": "content",
      "text": "Each session is stored in a Redis hash:\n\n[code example]\n\nThe implementation uses:\n\n* [`HSET`](https://redis.io/docs/latest/commands/hset) to create and update session fields\n* [`HGETALL`](https://redis.io/docs/latest/commands/hgetall) to load the session\n* [`HINCRBY`](https://redis.io/docs/latest/commands/hincrby) to update counters\n* [`EXPIRE`](https://redis.io/docs/latest/commands/expire) to implement sliding expiration\n* [`DEL`](https://redis.io/docs/latest/commands/del) to remove a session on logout\n\nThe store treats `created_at`, `last_accessed_at`, and `session_ttl` as reserved internal fields, so caller-provided session data cannot overwrite them."
    },
    {
      "id": "session-store-implementation",
      "title": "Session store implementation",
      "role": "content",
      "text": "The `create_session()` method generates a random session ID, writes the initial hash fields, and sets the TTL:\n\n[code example]\n\nWhen the application reads a session, it refreshes the configured TTL so active users stay logged in:\n\n[code example]\n\nThis is a simple and effective pattern for many apps. For more complex requirements, you might add separate metadata keys, rotate session IDs after login, or store less frequently accessed data elsewhere."
    },
    {
      "id": "installation",
      "title": "Installation",
      "role": "setup",
      "text": "Install the `redis` gem:\n\n[code example]\n\nOr add it to your `Gemfile`:\n\n[code example]\n\nThen run:\n\n[code example]"
    },
    {
      "id": "running-the-demo",
      "title": "Running the demo",
      "role": "content",
      "text": "A local demo server is included to show the session store in action\n([source](demo_server.rb)):\n\n[code example]\n\nThe demo exposes a small interactive page where you can:\n\n* Start a session with a username\n* Choose a short TTL and watch the session expire\n* See the Redis-backed session data rendered in the browser\n* Increment a page-view counter stored in Redis\n* Change the active session TTL from the page\n* Log out and delete the session\n\nThe demo assumes Redis is running on `localhost:6379`, but you can override that with `--redis-host` and `--redis-port`. After starting the server, visit `http://localhost:8080`."
    },
    {
      "id": "cookie-handling",
      "title": "Cookie handling",
      "role": "content",
      "text": "The browser cookie should contain only the session ID:\n\n[code example]\n\nAvoid storing user profiles, roles, or other sensitive session data directly in cookies. Keep that information in Redis and let the cookie act only as a lookup token."
    },
    {
      "id": "production-usage",
      "title": "Production usage",
      "role": "content",
      "text": "This guide uses a deliberately small local demo so you can focus on the Redis session pattern. In production, you will usually want to harden the cookie, session lifecycle, and deployment details around it."
    },
    {
      "id": "secure-the-session-cookie",
      "title": "Secure the session cookie",
      "role": "content",
      "text": "Set cookie attributes that match your deployment and threat model:\n\n* Keep `HttpOnly` enabled so JavaScript cannot read the session cookie\n* Use the `Secure` attribute when serving your app over HTTPS\n* Choose an appropriate `SameSite` policy for your login flow and cross-site behavior"
    },
    {
      "id": "keep-session-data-lightweight",
      "title": "Keep session data lightweight",
      "role": "content",
      "text": "Redis-backed sessions work best when each session stores small, frequently accessed values:\n\n* Usernames, IDs, and feature flags are a good fit\n* Large profiles, document blobs, or activity feeds should usually live elsewhere\n* Consider storing only references if the session needs to point to larger data"
    },
    {
      "id": "handle-expiration-deliberately",
      "title": "Handle expiration deliberately",
      "role": "content",
      "text": "Sliding expiration is convenient, but it also defines how long a hijacked cookie remains useful. For production apps, consider:\n\n* Shorter inactivity TTLs for sensitive applications\n* Separate absolute expiration limits for long-lived sessions\n* Session ID rotation after login or privilege changes"
    },
    {
      "id": "use-a-framework-integration-where-appropriate",
      "title": "Use a framework integration where appropriate",
      "role": "content",
      "text": "This example keeps everything explicit so you can see the Redis session pattern clearly. In a real app, you will often wrap the same Redis operations behind middleware for Rails, Sinatra, Hanami, or another Rack-based framework."
    },
    {
      "id": "next-steps",
      "title": "Next steps",
      "role": "content",
      "text": "You now have a complete Redis-backed session example in Ruby using `redis-rb`. From here you can:\n\n* Adapt the store to your web framework\n* Add session ID rotation or absolute expiration\n* Store additional lightweight session metadata in the same Redis hash\n* Reuse the same Redis deployment across multiple application instances\n\nFor more Redis data modeling patterns, see:\n\n* [Session store overview](https://redis.io/docs/latest/develop/use-cases/session-store)\n* [Ruby client guide](https://redis.io/docs/latest/develop/clients/ruby)\n* [Redis data types](https://redis.io/docs/latest/develop/data-types)"
    }
  ],
  "examples": [
    {
      "id": "the-ruby-session-store-ex0",
      "language": "ruby",
      "code": "require \"redis\"\nrequire_relative \"session_store\"\n\nredis = Redis.new(host: \"localhost\", port: 6379)\nstore = RedisSessionStore.new(redis: redis, ttl: 1800)\n\nsession_id = store.create_session(\n  {\n    username: \"andrew\",\n    page_views: \"0\"\n  }\n)\n\nsession = store.get_session(session_id)\nputs session[\"username\"]\n\nstore.increment_field(session_id, \"page_views\")\nstore.delete_session(session_id)",
      "section_id": "the-ruby-session-store"
    },
    {
      "id": "data-model-ex0",
      "language": "text",
      "code": "session:abc123...\n  username = andrew\n  page_views = 3\n  session_ttl = 15\n  created_at = 2026-04-08T12:34:56Z\n  last_accessed_at = 2026-04-08T12:40:10Z",
      "section_id": "data-model"
    },
    {
      "id": "session-store-implementation-ex0",
      "language": "ruby",
      "code": "def create_session(data = {}, ttl: nil)\n  session_id = SecureRandom.urlsafe_base64(32)\n  key = session_key(session_id)\n  now = timestamp\n  session_ttl = normalize_ttl(ttl)\n\n  payload = user_payload(data).merge(\n    \"created_at\" => now,\n    \"last_accessed_at\" => now,\n    \"session_ttl\" => session_ttl.to_s\n  )\n\n  @redis.pipelined do |pipeline|\n    pipeline.hset(key, payload)\n    pipeline.expire(key, session_ttl)\n  end\n\n  session_id\nend",
      "section_id": "session-store-implementation"
    },
    {
      "id": "session-store-implementation-ex1",
      "language": "ruby",
      "code": "def get_session(session_id, refresh_ttl: true)\n  key = session_key(session_id)\n  session = @redis.hgetall(key)\n  return nil unless valid_session?(session)\n\n  return session unless refresh_ttl\n\n  session_ttl = normalize_ttl(Integer(session[\"session_ttl\"]))\n  result = @redis.pipelined do |pipeline|\n    pipeline.hset(key, \"last_accessed_at\", timestamp)\n    pipeline.expire(key, session_ttl)\n    pipeline.hgetall(key)\n  end\n\n  refreshed = result[2] || {}\n  valid_session?(refreshed) ? refreshed : nil\nend",
      "section_id": "session-store-implementation"
    },
    {
      "id": "installation-ex0",
      "language": "bash",
      "code": "gem install redis",
      "section_id": "installation"
    },
    {
      "id": "installation-ex1",
      "language": "ruby",
      "code": "gem \"redis\", \"~> 5.0\"",
      "section_id": "installation"
    },
    {
      "id": "installation-ex2",
      "language": "bash",
      "code": "bundle install",
      "section_id": "installation"
    },
    {
      "id": "running-the-demo-ex0",
      "language": "bash",
      "code": "gem install redis webrick\nruby demo_server.rb",
      "section_id": "running-the-demo"
    },
    {
      "id": "cookie-handling-ex0",
      "language": "ruby",
      "code": "cookie = WEBrick::Cookie.new(\"sid\", session_id)\ncookie.path = \"/\"\ncookie.httponly = true\nres.cookies << cookie",
      "section_id": "cookie-handling"
    }
  ]
}
