Skip to main content

Command Palette

Search for a command to run...

Redis as a Session Store for Scalable Web Architecture

How Redis enables fast, secure, and scalable session management in modern PHP-based web applications.

Updated
5 min read
Redis as a Session Store for Scalable Web Architecture

Series: Web Authentication Demystified — From Concepts to Real-World

In traditional PHP applications, sessions often feel invisible. You enable them, they work, and you move on. But once an application grows beyond a single server—especially when authentication is involved—where and how sessions are stored becomes a critical architectural decision.

In my CSL system (which is powered by a PHP framework - Yii, or more specifically, Humhub), Redis plays a central role: it is the backbone that allows a hybrid OIDC + PHP session model to scale horizontally while remaining secure, fast, and operationally simple.

This article explains:

  • why default file-based sessions don’t scale

  • how Redis changes the session model

  • how Yii/HumHub integrates with Redis sessions

  • what data is actually stored

  • how Redis enables instant logout and revocation

  • real-world pitfalls and best practices


The Problem with Traditional PHP Sessions

By default, PHP stores sessions as files on disk:

/tmp/sess_abcd1234

This works fine when:

  • you have one server

  • users don’t move between machines

  • traffic is low

But it breaks down quickly in modern environments.

Key Limitations

  • Sessions are local to one server

  • Load balancers must use sticky sessions

  • Horizontal scaling becomes painful

  • Session cleanup is slow and unreliable

  • Disk I/O becomes a bottleneck

  • Revoking sessions across servers is hard

In a system like CSL—with:

  • multiple app servers

  • Redis-backed auth

  • CloudFront

  • government IdP integration

file-based sessions simply aren’t enough.


Why Redis Is a Natural Fit for Sessions

Redis is an in-memory key–value store designed for speed, simplicity, and predictability.

For session storage, Redis offers exactly what we need:

  • shared state across servers

  • extremely fast reads/writes

  • built-in expiration (TTL)

  • atomic operations

  • simple data model

  • mature ecosystem

Instead of:

“Session lives on this server”

Redis enables:

“Session lives wherever Redis is reachable”


What a Redis-Backed Session Looks Like

Conceptually, a PHP session stored in Redis looks like this:

Key: humhub_sess_abcd1234
TTL: 3600 seconds
Value:
{
  "user_id": 4821,
  "role": "teacher",
  "login_time": 1733640000,
  "permissions": [...]
}

Important details:

  • The session ID remains in the browser (PHPSESSID)

  • The actual session data lives in Redis

  • Redis handles expiration automatically

  • Any app server can load the session


How Redis Fits into the CSL Authentication Flow

In CSL, Redis sessions are created after OIDC authentication succeeds.

The flow:

  1. User authenticates via IdP

  2. Backend validates token

  3. Identity is mapped to local user

  4. PHP session is created and stored in Redis

  5. Browser receives PHPSESSID cookie

  6. Every subsequent request:

    • browser sends PHPSESSID

    • backend loads session from Redis

Redis becomes the single source of truth for authenticated state.


Configuring Redis Sessions in Yii / HumHub

Yii provides first-class support for Redis-backed sessions.

A simplified configuration looks like this:

'components' => [
    'redis' => [
        'class' => 'yii\redis\Connection',
        'hostname' => 'redis.internal',
        'port' => 6379,
        'database' => 0,
    ],
    'session' => [
        'class' => 'yii\redis\Session',
        'redis' => 'redis',
        'keyPrefix' => 'humhub_sess_',
        'timeout' => 3600,
    ],
]

From this point on:

  • Yii::$app->session transparently uses Redis

  • No code changes are needed in controllers

  • HumHub continues to work as-is

This is one of the reasons Redis works so well with legacy PHP systems.


Session Creation During Login (Real Example)

After OIDC authentication and identity mapping:

Yii::$app->user->switchIdentity($user, 0);

// Prevent session fixation
Yii::$app->session->regenerateID(true);

// Store useful context
Yii::$app->session->set('login_time', time());
Yii::$app->session->set('auth_source', 'government-idp');
Yii::$app->session->set('user_role', $user->role);

Redis automatically:

  • stores the session

  • sets TTL

  • replicates state across app servers


Why Redis Enables Horizontal Scaling

Without Redis:

  • each server holds its own sessions

  • users must stick to one server

With Redis:

  • any server can serve any request

  • load balancer can route freely

  • scaling is trivial

This makes Redis essential for:

  • autoscaling groups

  • containerized deployments

  • rolling deployments

  • blue/green releases


Instant Logout and Session Revocation

One of Redis’ biggest advantages is centralized revocation.

Logging out a user:

Yii::$app->session->destroy();

This immediately:

  • deletes the Redis key

  • invalidates the session everywhere

  • blocks access on all servers

Compare that to JWT-based systems, where tokens remain valid until expiration.


Session Expiration and TTL

Redis sessions naturally expire via TTL.

Typical strategies:

  • 30–60 minutes idle timeout

  • session TTL refreshed on activity

  • absolute session lifetime enforced in code

Example:

Yii::$app->session->setTimeout(3600);

Redis handles cleanup automatically—no cron jobs, no disk sweeps.


Security Benefits of Redis Sessions

No Tokens in the Browser

Only a random session ID is stored in the cookie.

HttpOnly Cookies

JS cannot access session data.

Central Authority

The backend decides who is logged in.

Reduced Attack Surface

No JWT parsing, no token replay, no localStorage risks.


Redis vs JWT: A Practical Comparison

AspectRedis SessionsJWT
Stateless
Revocation✅ Immediate❌ Hard
Browser storageCookie IDToken
XSS impactLowHigh
Scaling
PHP-friendly⚠️

In CSL’s context, Redis sessions win decisively.


Operational Considerations

High Availability

  • Use Redis replication

  • Consider Redis Sentinel or managed Redis

Persistence

  • Enable RDB or AOF to survive restarts

Memory Management

  • Set max memory

  • Use eviction policies carefully

Monitoring

  • Track memory usage

  • Track session count

  • Watch eviction events


Common Pitfalls to Avoid

  • Storing large blobs in session

  • Infinite TTL sessions

  • Relying on Redis as a database

  • Ignoring Redis downtime scenarios

  • Not regenerating session IDs on login


Why Redis Was the Right Choice for CSL

Redis allowed CSL to:

  • scale authentication horizontally

  • preserve PHP’s session model

  • integrate cleanly with OIDC

  • support instant logout

  • reduce frontend security risks

  • keep architecture simple and maintainable

It wasn’t a “modern” choice—it was a correct one.


Final Thoughts

Redis sessions sit quietly behind the scenes, but they’re one of the most important components in a secure, scalable web authentication system. In CSL, Redis bridges the gap between modern identity standards and a traditional PHP architecture—without forcing either side to compromise.

Web Authentication Demystified — From Concepts to Real-World

Part 2 of 14

This series breaks down modern web authentication, from core concepts like OAuth, OIDC, and tokens to real implementation details. You’ll learn how the pieces fit together and see how a production-ready system is built and secured.

Up next

CloudFront Signed Cookies — How They Work and Why We Used Them

How signed cookies extend authentication to the CDN layer and securely protect static assets in a real-world system.