---
title: Asena Redis
description: Redis integration with @Redis - cache decorators (@Cacheable, @CachePut, @CacheEvict), multi-pod WebSocket transport and a Redis Streams microservice transport with consumer groups, retry and DLQ
outline: deep
---

# Asena Redis

Redis integration for AsenaJS — service client with cache decorators and built-in multi-pod WebSocket transport. Your `@Redis` decorated service gives you full Redis operations with automatic IoC registration. [`@Cacheable`, `@CachePut` and `@CacheEvict`](#caching-decorators) put a caching policy on a service method. For multi-pod deployments, `RedisTransport` synchronizes WebSocket messages across instances via Redis pub/sub.

<div class="card-grid">
  <a class="info-card" href="#quick-start">
    <span class="ic-kicker">01</span>
    <div class="ic-title">Quick Start</div>
    <p class="ic-desc">The <code>@Redis</code> service, connected and injected.</p>
  </a>
  <a class="info-card" href="#adapter-selection">
    <span class="ic-kicker">02</span>
    <div class="ic-title">Adapter Selection</div>
    <p class="ic-desc">Bun native <code>RedisClient</code> or the node-redis package.</p>
  </a>
  <a class="info-card" href="#api-reference">
    <span class="ic-kicker">03</span>
    <div class="ic-title">API Reference</div>
    <p class="ic-desc">String, hash, set, key and raw command support.</p>
  </a>
  <a class="info-card" href="#configuration">
    <span class="ic-kicker">04</span>
    <div class="ic-title">Configuration</div>
    <p class="ic-desc">Connection options and lifecycle settings.</p>
  </a>
  <a class="info-card" href="#caching-decorators">
    <span class="ic-kicker">05</span>
    <div class="ic-title">Caching Decorators</div>
    <p class="ic-desc"><code>@Cacheable</code>, <code>@CachePut</code> and <code>@CacheEvict</code> on service methods.</p>
  </a>
  <a class="info-card" href="#multi-pod-websocket-transport">
    <span class="ic-kicker">06</span>
    <div class="ic-title">Multi-Pod WebSocket</div>
    <p class="ic-desc">Synchronizing socket messages across pods via pub/sub.</p>
  </a>
  <a class="info-card" href="#microservice-transport-redis-streams">
    <span class="ic-kicker">07</span>
    <div class="ic-title">Microservice Transport</div>
    <p class="ic-desc">Service-to-service messaging over Redis Streams.</p>
  </a>
</div>

## Features

- **Decorator-Based Setup** - `@Redis` decorator handles IoC registration and connection lifecycle
- **Declarative Caching** - `@Cacheable`, `@CachePut` and `@CacheEvict` with class-level `@CacheConfig`
- **Dual Adapter Support** - Bun native `RedisClient` (default) and `redis` (node-redis) package
- **Multi-Pod WebSocket Transport** - Synchronize WebSocket messages across pods via Redis pub/sub
- **Full Redis Operations** - String, Hash, Set, Key, and raw command support
- **Binary Data Support** - ArrayBuffer and Uint8Array transport with Base64 encoding
- **Zero Runtime Dependencies** - Only peer deps (asena, reflect-metadata)

## Installation

```bash
bun add @asenajs/asena-redis
```

For node-redis adapter (optional):
```bash
bun add @asenajs/asena-redis redis
```

**Requirements:**
- [Bun](https://bun.sh) v1.4 or higher
- [@asenajs/asena](https://github.com/AsenaJs/Asena) v0.11.0 or higher

## Quick Start

### 1. Create Redis Service

```typescript
import { Redis, AsenaRedisService } from '@asenajs/asena-redis';

@Redis({
  config: { url: 'redis://localhost:6379' },
  name: 'AppRedis',
})
export class AppRedis extends AsenaRedisService {}
```

Asena automatically discovers it — that's it.

#### Lazy options

`@Redis` also accepts a **thunk**, resolved when the service is constructed rather than when the
class is defined. That is what lets a Redis service live in a shared package and still read the
consuming application's environment:

```typescript
@Redis(() => ({ config: { url: process.env.REDIS_URL } }))
export class AppRedis extends AsenaRedisService {}
```

A thunk cannot carry a `name` — the options do not exist yet when the decorator registers the
class — so the thunk form registers under the **decorated class's own name**. Use the object form
with `name` to choose the registration key explicitly. Nothing outside the thunk's return value is
mutated.

::: tip Composes with `imports`
A `@Redis` service in a package is registered by handing it to
[`imports`](/docs/concepts/dependency-injection#registering-components-from-packages); the thunk
is what lets that package read the consumer's environment at the right moment.
:::

### 2. Inject and Use

```typescript
import { Service } from '@asenajs/asena/decorators';
import { Inject } from '@asenajs/asena/decorators/ioc';

@Service()
export class GreetingService {

  @Inject('AppRedis')
  private redis: AppRedis;

  async greet(name: string): Promise<string> {
    await this.redis.set(`greeting:${name}`, `Hello, ${name}`, 60);

    return (await this.redis.get(`greeting:${name}`)) ?? '';
  }

}
```

To cache a method's result, use the [caching decorators](#caching-decorators) rather than writing
the read, compute and write steps by hand.

::: tip Connection lifecycle is handled for you
`AsenaRedisService` carries an [`@OnStart`](/docs/concepts/lifecycle) that connects during
`server.start()`, and an `@OnStop` that closes on `server.stop()` — first every connection handed
out by `createSubscriber()`, then the main client. Failures on individual subscribers are logged
and stepped over so one dead socket cannot strand the others or the main client.

A **user-supplied `client`** (the `client` option) is closed too: `@OnStart` adopts it as the
connection the service runs on, and `@OnStop` treats it the same way. If you need to keep it
alive past the server, do not hand it to `@Redis`.
:::

## Adapter Selection

By default, `@asenajs/asena-redis` uses Bun's native `RedisClient`. For environments requiring the `redis` (node-redis) package:

```typescript
@Redis({
  config: { url: 'redis://localhost:6379' },
  adapter: 'node-redis',
})
export class AppRedis extends AsenaRedisService {}
```

| Adapter | Package | Best For |
|:--------|:--------|:---------|
| `'bun'` (default) | None (Bun built-in) | Bun runtime, maximum performance |
| `'node-redis'` | `redis` ^5.12.1 | Node.js compatibility, Redis modules |

Both adapters reconnect on their own when the connection drops. The node-redis adapter logs one
`NodeRedisAdapter: Redis connection error: ...` line on `console.error` per outage, not one per
reconnect attempt.

## API Reference

### String Operations

| Method | Parameters | Returns | Description |
|:-------|:-----------|:--------|:------------|
| `get(key)` | `key: string` | `string \| null` | Get string value |
| `set(key, value, ttl?)` | `key: string, value: string, ttl?: number` | `void` | Set value with optional TTL (seconds) |
| `del(...keys)` | `...keys: string[]` | `number` | Delete keys, returns count |
| `exists(key)` | `key: string` | `boolean` | Check if key exists |
| `incr(key)` | `key: string` | `number` | Increment counter |
| `decr(key)` | `key: string` | `number` | Decrement counter |
| `expire(key, seconds)` | `key: string, seconds: number` | `void` | Set expiration |
| `ttl(key)` | `key: string` | `number` | Get remaining TTL |
| `keys(pattern)` | `pattern: string` | `string[]` | Find keys by pattern |

### Hash Operations

| Method | Parameters | Returns | Description |
|:-------|:-----------|:--------|:------------|
| `hget(key, field)` | `key: string, field: string` | `string \| null` | Get hash field |
| `hmset(key, fields)` | `key: string, fields: string[]` | `void` | Set multiple fields (`['f1', 'v1', 'f2', 'v2']`) |
| `hmget(key, fields)` | `key: string, fields: string[]` | `(string \| null)[]` | Get multiple fields |

### Set Operations

| Method | Parameters | Returns | Description |
|:-------|:-----------|:--------|:------------|
| `sadd(key, member)` | `key: string, member: string` | `number` | Add member to set |
| `srem(key, member)` | `key: string, member: string` | `number` | Remove member from set |
| `smembers(key)` | `key: string` | `string[]` | Get all members |
| `sismember(key, member)` | `key: string, member: string` | `boolean` | Check membership |

### Raw & Lifecycle

| Method | Parameters | Returns | Description |
|:-------|:-----------|:--------|:------------|
| `send(command, args)` | `command: string, args: string[]` | `any` | Execute raw Redis command |
| `ping(timeoutMs?)` | `timeoutMs: number` (default `1000`) | `'PONG'` | Send `PING`, or reject with `Redis PING timed out after <n>ms` |
| `client` | — | `RedisClientAdapter` | Access underlying client |
| `createSubscriber()` | — | `RedisClientAdapter` | Create duplicate connection for pub/sub. Tracked by the service and closed on `server.stop()` |
| `testConnection()` | — | `boolean` | `true` when connected and a `PING` came back within `ping()`'s timeout; `false` otherwise |
| `disconnect()` | — | `void` | Close the main connection. Called for you by `@OnStop`; calling it by hand leaves any subscriber you are still reading from open |

::: warning `ping()` is bounded on purpose
With the offline queue enabled — the default in most clients — a command issued against an
unreachable Redis does not fail. It waits in the queue for a connection that may never come, so an
unbounded readiness probe **hangs forever** instead of reporting "down", which is the opposite of
what a probe is for.

`ping()` races the command against a `1000` ms timer (configurable) and rejects when the timer
wins. `testConnection()` now goes through it, so a probe against an unreachable Redis returns
`false` after at most a second instead of never returning. It still returns `false` immediately
when the client reports itself disconnected.
:::

### Redis Streams Helpers

The package exports the same thin, client-agnostic wrappers over the Redis Streams commands that
the [microservice transport](#microservice-transport-redis-streams) uses. They take any
`RedisClientAdapter` and normalize the RESP2 (node-redis) and RESP3 (Bun) reply shapes, so
consumer code never branches on the adapter:

| Export | Purpose |
|:-------|:--------|
| `xadd`, `xrange`, `xack` | Append, read a range, acknowledge |
| `xgroupCreate`, `xgroupDelConsumer`, `xreadgroup` | Consumer group lifecycle and reads |
| `xpending`, `xpendingConsumer`, `xinfoConsumers`, `xclaim` | Pending-entry inspection and reclaim |
| `entryTimestamp` | Creation time (epoch ms) extracted from an entry id |
| `normalizeStreamsReply`, `normalizeEntries`, `normalizeFields` | The reply normalizers, for hand-rolled commands |
| `StreamEntry`, `PendingEntry`, `ConsumerInfo` | The types they return |

```typescript
import { xrange } from '@asenajs/asena-redis';

const recent = await xrange(redis.client, 'orders', '-', '+', 10);

for (const entry of recent) {
  console.log(entry.id, entry.fields);
}
```

`xrange(client, key, start = '-', end = '+', count?)` reads entries by id range — `'-'` / `'+'`
for the ends, `'<ms>-<seq>'` for a point, a `'('` prefix for exclusive — and returns
`StreamEntry[]` (`{ id, fields }`) in id order. It is new; the rest were internal to the transport
and are now public, so a DLQ inspector or a backfill script no longer has to re-implement the
RESP2/RESP3 normalisation.

## Configuration

### RedisConfig

```typescript
interface RedisConfig {
  // Connection
  url?: string;                // redis[s]://[[username][:password]@][host][:port][/db]
  host?: string;               // default: 'localhost'
  port?: number;               // default: 6379
  username?: string;
  password?: string;
  db?: number;

  // Timeouts & Reconnection
  connectionTimeout?: number;  // Connection timeout in ms (default: 10000)
  idleTimeout?: number;        // Idle timeout in ms (Bun only, default: 0)
  autoReconnect?: boolean;     // Auto-reconnect on disconnect (default: true)
  maxRetries?: number;         // Max reconnection attempts (default: 10)

  // Behavior
  enableOfflineQueue?: boolean;     // Queue commands when disconnected (default: true)
  enableAutoPipelining?: boolean;   // Automatic command pipelining (Bun only, default: true)

  // TLS
  tls?: boolean | TLSOptions;

  // Identification
  name?: string;               // Service name for logging
}
```

::: info Bun-Only Features
`idleTimeout` and `enableAutoPipelining` are Bun-only features and are silently ignored when using the `node-redis` adapter.
:::

### @Redis Decorator Options

```typescript
@Redis({
  config: RedisConfig,         // Redis connection configuration
  adapter?: 'bun' | 'node-redis', // Client adapter (default: 'bun')
  name?: string,               // Service name for IoC registration
})
```

It also accepts `() => RedisOptions` — the same object, resolved at construction time. See
[Lazy options](#lazy-options).

## Caching Decorators

Declarative caching for service methods: `@Cacheable`, `@CachePut` and `@CacheEvict` put the policy
on the method instead of repeating the read, compute and write steps inside it.

### Activation

`CachePostProcessor` does the wrapping. It carries no `@PostProcessor` and component scanning never
walks `node_modules`, so caching is activated by subclassing it in your source folder —
`src/config/` is the convention:

```typescript
// src/config/AppCache.ts
import { RedisCache, CachePostProcessor } from '@asenajs/asena-redis';

@RedisCache({ ttl: 300 })
export class AppCache extends CachePostProcessor {}
```

The body stays empty; the class only has to exist for scanning to find it. The options are the
application-wide defaults, and `@RedisCache()` with none is valid. The application also needs a
[`@Redis` service](#_1-create-redis-service) for the cache to use.

::: warning Nothing is cached without this class
Without a `@RedisCache` class the decorators record metadata that nothing reads: every call runs the
method, with no error and no warning. An application that passes an explicit component list, such as
a [`createTestApp`](/docs/testing/test-app) test, has to list the class too.

Declare one. Each `@RedisCache` class wraps the methods again and writes its own entries.
:::

### Usage

```typescript
import { Service } from '@asenajs/asena/decorators';
import { Inject } from '@asenajs/asena/decorators/ioc';
import { Cacheable, CachePut, CacheEvict, CacheConfig } from '@asenajs/asena-redis';

@Service()
@CacheConfig({ prefix: 'user' })
export class UserService {

  @Inject(UserRepository)
  private users: UserRepository;

  @Cacheable({ key: (id: string) => id })
  async findById(id: string): Promise<User | null> {
    return this.users.findById(id);
  }

  @CachePut({ key: (id: string) => id })
  async refresh(id: string): Promise<User | null> {
    return this.users.findById(id);
  }

  @CacheEvict({ key: (id: string) => id })
  async update(id: string, changes: UserChanges): Promise<void> {
    await this.users.update(id, changes);
  }

  @CacheEvict({ allEntries: true })
  async removeAll(): Promise<void> {
    await this.users.removeAll();
  }

}
```

`@CacheConfig` sets defaults for every cache decorator in the class. A `@Cacheable` hit on `user:42`
skips `findById`, `refresh('42')` overwrites that entry, `update('42', ...)` deletes it, and
`removeAll()` deletes every key under `user:`.

::: warning Methods that share an entry must build the same key
The default key contains the method name, so a bare `@CacheEvict()` on `update` never touches what a
bare `@Cacheable()` on `findById` stored, and nothing reports the miss. When one method reads an
entry and another replaces or deletes it, give both the same `key` and the same `prefix`.
:::

### Semantics

| | Method runs | Reads cache | Writes cache | If the method throws |
|:--|:--|:--|:--|:--|
| `@Cacheable` | only on a miss | before the call | after success, on a miss | no write, error propagates |
| `@CachePut` | always | never | after success | no write, error propagates |
| `@CacheEvict` | always | never | deletes **after** success | **no eviction**, error propagates |
| `@CacheEvict({ beforeInvocation: true })` | always | never | deletes **before** the call | eviction already happened, error propagates |

Several decorators on one method produce a single wrapper, in a fixed order:
`evict(before) → read → method → write → evict(after)`. A `@Cacheable` hit returns straight away and
skips everything after the read, including an after-success eviction. `@Cacheable` and `@CachePut`
on the same method contradict each other and fail the boot.

The wrapper is installed on the instance, which has two consequences:

- **Calls from inside the class are cached too.** `this.findById(id)` goes through the wrapper the
  same way an injected caller does.
- **Decorators are inherited.** A subclass inherits the decorators on its base class's methods, and
  an override without a decorator is still wrapped with the inherited options. A decorator of the
  same kind on the override replaces them. `@CacheConfig` merges field by field, nearest class first.

### Options

`redis`, `prefix`, `ttl` and `timeout` can be set at three levels and resolve independently,
nearest level first: `method option > @CacheConfig > @RedisCache`. A method that overrides only
`ttl` keeps the class's `prefix`. The other options exist only on the method decorators.

| Option | Applies to | Meaning |
|:--|:--|:--|
| `key` | `@Cacheable`, `@CachePut`, `@CacheEvict` | `(...args) => string`, receiving the method's arguments and returning a non-empty string. Omitted → `` `${Class.name}.${method}:${JSON.stringify(args)}` ``. Ignored with `allEntries` |
| `prefix` | all three, `@CacheConfig`, `@RedisCache` | Key namespace, joined with `:`; a trailing `:` is not doubled. Also the scope of `allEntries`. Omitted → no prefix |
| `ttl` | `@Cacheable`, `@CachePut`, `@CacheConfig`, `@RedisCache` | **Seconds**, a positive whole number up to `Number.MAX_SAFE_INTEGER` (`9007199254740991`). Unset at every level means the entry never expires |
| `redis` | all three, `@CacheConfig`, `@RedisCache` | Name the `@Redis` service is registered under. Omit it when exactly one is registered |
| `timeout` | all three, `@CacheConfig`, `@RedisCache` | **Milliseconds**, a positive number up to `2147483647`, the largest delay a timer holds: the limit on each Redis command the cache sends. A command past it counts as failed. Default `500`. See [Time limit](#time-limit) |
| `cacheNull` | `@Cacheable`, `@CachePut` | Store `null` and `undefined` results, which then count as hits. Default `true` |
| `allEntries` | `@CacheEvict` | Delete every key under the prefix, via `SCAN`, instead of one key. Requires a prefix. Default `false` |
| `beforeInvocation` | `@CacheEvict` | Evict before the method runs rather than after it succeeds. Default `false` |

A level closer to the method can replace `ttl` but cannot remove it: `ttl: undefined` falls through
to the next level, so a method that must never expire needs the levels above it to leave `ttl` unset.

There is no string key expression language. A `key` function is as short as a template, needs no
grammar and cannot fail on a malformed expression. TypeScript does not check its parameters against
the method's, so keep the two in step by hand.

The default key is built from the class name, so a build that mangles identifiers changes it, and
two subclasses of one base never share entries. It also serializes every argument, so pass a `key`
function for a method whose arguments are large or carry fields that do not identify the result.

### Failure Policy

**Runtime Redis failures fail open.** A command error, a client that has not started, a corrupt entry
or a foreign value under the key each produce a `[RedisCache]` warning on the framework logger, and
the call carries on as though there were no cache. A cache outage must not become an application
outage.

A failed read runs the method and skips the write for that call. A failed write or eviction still
returns the method's result. The cost lands on eviction: when `@CacheEvict` cannot reach Redis, the
old entry stays until its `ttl` runs out or something overwrites it.

#### Time limit

Every Redis command the cache sends has a time limit, set with the `timeout` option in milliseconds
(default `500`). It applies to each command on its own: every `GET`, `SET` and `DEL`, and each `SCAN`
round and delete batch of an `allEntries` eviction, so a long sweep on a healthy server is not cut
short. A command past the limit counts as failed, with the same warning and the same outcome as any
other failed command:

```text
[RedisCache] cache read for 'user:42' failed, running the method instead: GET timed out after 500ms
```

This is what makes the cache fail open while Redis is down. With the client's offline queue on, the
default for both adapters, a command issued during an outage does not fail; it waits in the queue
for a reconnect. The limit stops the cached call from waiting with it: during an outage a call waits
at most the limit for each command it sends, and since a failed read skips the write, a `@Cacheable`
miss costs one limit.

A command that times out is not cancelled: one waiting in the offline queue is sent once the
connection returns. See [Limitations](#limitations) for what a late `SET` can do.

::: tip The offline queue on a cache-only service
Failing open does not depend on the queue, but turning it off with `enableOfflineQueue: false`
changes what an outage costs. A command issued while the client knows it is disconnected
fails straight away instead of waiting out the limit, and nothing is queued to land after the
reconnect:

```typescript
@Redis({
  config: { url: 'redis://localhost:6379', enableOfflineQueue: false },
  name: 'CacheRedis',
})
export class CacheRedis extends AsenaRedisService {}

@RedisCache({ redis: 'CacheRedis', ttl: 300 })
export class AppCache extends CachePostProcessor {}
```

The setting covers everything that uses that service, so give the cache its own `@Redis` service when
something else relies on the queue.
:::

A client that stops reconnecting, such as the Bun client once `maxRetries` runs out, stays closed:
every cached call warns and runs the method until the process restarts.

#### Mistakes in the code

Mistakes in the code are not contained. They are bugs, and they say so. These fail the boot:

- `@Cacheable` and `@CachePut` on the same method
- `allEntries` with no prefix at any level, which would otherwise delete every key in the database
- a `ttl` that resolves to anything but a positive whole number of seconds up to `9007199254740991`
- a `timeout` that resolves to anything but a positive number of milliseconds up to `2147483647`
- a cache decorator on a name that holds no function on the instance

These reject the call, with the error reaching the caller:

- a `key` function that throws, or returns anything but a non-empty string
- a default key over arguments that cannot be serialized (circular, `BigInt`)
- a Redis service that cannot be picked (see below)

With `@Cacheable` the method has not run when one of these rejects. With an after-success
`@CacheEvict`, and with `@CachePut` when the Redis service cannot be picked, it has: its work stands
even though the caller sees an error.

::: warning Wiring mistakes surface on the first cached call, not at boot
A post-processor sees the component graph while it is still being built, and core has no later
hook, so the cache picks its Redis service on the call. These mistakes reject cached calls instead
of failing the boot:

- no `@Redis` service is registered;
- more than one is registered and the decorators do not name one;
- the named service does not exist;
- the service was replaced by something that is not an `AsenaRedisService`, such as a plain test
  double registered through `overrides`.

The error is thrown before the method runs for `@Cacheable` and for `@CacheEvict` with
`beforeInvocation`, and after the method has run for `@CachePut` and `@CacheEvict`.

Name the service explicitly whenever the application has more than one, and exercise one cached
endpoint in staging before you ship.
:::

### Limitations

- **A cached value is whatever survives `JSON.parse(JSON.stringify(x))`.** A `Date` comes back as a
  string, a `Map` or `Set` as `{}`, a class instance as a plain object. The miss that computed it
  still returns the original, so one method can return two shapes for one key. A value that cannot be
  serialized at all (circular, `BigInt`) is returned to the caller with the write skipped and a
  warning.
- **Wrapped methods always return a Promise.** The cache read has to be awaited, so a synchronous
  method becomes asynchronous.
- **The decorators are typed for methods**, so TypeScript rejects them on an arrow-function
  property. Applied to one anyway (plain JavaScript, or Bun running without a type check), the
  property is wrapped and cached like a method and keeps its `this`.
- **A command that times out is not cancelled.** With the client's offline queue on, it is sent when
  the connection returns: a late `SET` stores the value computed during the outage with a fresh
  `ttl`, and can overwrite a newer entry written after the reconnect, for example by another
  instance of the application.
- **`allEntries` deletes everything under the prefix**, including keys written by other classes that
  share it and keys the cache never wrote. `SCAN` is not a snapshot, so a key written mid-scan may
  survive until its `ttl`. On Redis Cluster it only covers the node it reaches. The walk runs inside
  the call, so a large prefix makes that call slow.
- **No stampede protection.** Concurrent misses on the same key all run the method. Per-process
  deduplication would not help the cross-pod case, which is the one that overloads a database.
- **A slow miss can undo an eviction.** A `@Cacheable` miss that read the old data and writes after a
  concurrent `@CacheEvict` stores a stale entry until its `ttl`, which is one more reason to set one.
- **A class in a post-processor's dependency closure is not wrapped.** Such a class is created in
  [Phase A](/docs/concepts/post-processor#bootstrap-priority), before post-processing is active, so
  its cache decorators silently do nothing. Keep cached services out of what your post-processors
  inject.

## Multi-Pod WebSocket Transport

`RedisTransport` synchronizes WebSocket messages across multiple server instances using Redis pub/sub. This enables room-based messaging, broadcasting, and direct socket messaging to work seamlessly across pods.

### Setup

Configure the transport in your `@Config` class's `transport()` method:

```typescript
import { Config } from '@asenajs/asena/decorators';
import { Inject } from '@asenajs/asena/decorators/ioc';
import { ConfigService } from '@asenajs/hono-adapter'; // or '@asenajs/ergenecore'
import { RedisTransport } from '@asenajs/asena-redis';

@Config()
export class AppConfig extends ConfigService {

  @Inject('AppRedis')
  private redis: AppRedis;

  public transport() {
    return new RedisTransport(this.redis);
  }

}
```

Or without an existing Redis service:

```typescript
public transport() {
  return new RedisTransport({ url: 'redis://localhost:6379' });
}
```

### How It Works

Each server instance gets a unique pod ID. When a message is published through the server (the service-level `this.to()` / `this.in()`):

1. The message is delivered locally via `server.publish()`
2. The message is sent to Redis pub/sub with the originating pod ID
3. Other pods receive the message and deliver it to their local sockets
4. Messages from the same pod are deduplicated automatically

`ws.publish()` takes a different route: it [excludes the sender](/docs/concepts/websocket#publishing-messages), so it does the local delivery itself and hands the transport only step 2 onwards via `publishRemote()`. Steps 3 and 4 are unchanged.

### Options

```typescript
new RedisTransport(source, {
  channel: 'asena:ws:transport', // Redis pub/sub channel (default)
});
```

::: tip No Code Changes Needed
Your WebSocket services, Ulak messaging, and room management work exactly the same with `RedisTransport`. The transport layer is transparent — just configure it in `@Config` and multi-pod support is enabled automatically.
:::

## Microservice Transport (Redis Streams)

`RedisMicroserviceTransport` is the production-grade broker implementation for Asena's [microservice layer](/docs/concepts/microservices) — request/response and events between independent Asena services, built on Redis Streams consumer groups.

### Setup

```typescript
import { Config } from '@asenajs/asena/decorators';
import { RedisMicroserviceTransport } from '@asenajs/asena-redis';

@Config()
export class AppConfig extends ConfigService {
  public transport() {
    return {
      microservice: new RedisMicroserviceTransport(
        { url: 'redis://localhost:6379' },
        { serviceName: 'order-service' }, // serviceName REQUIRED - consumer group identity
      ),
    };
  }
}
```

`serviceName` is the consumer group: all replicas of the same service **must** share it, different services **must** differ (each service group receives its own copy of every event).

### Reusing Your @Redis Service

If your app already has a `@Redis` service, you do not need to repeat the connection settings. Inject it into the config class and pass it where the config object would go — the transport then reuses its connection instead of opening its own:

```typescript
import { Config } from '@asenajs/asena/decorators';
import { Inject } from '@asenajs/asena/decorators/ioc';
import { ConfigService } from '@asenajs/hono-adapter'; // or '@asenajs/ergenecore'
import { RedisMicroserviceTransport } from '@asenajs/asena-redis';
import { AppRedis } from '../redis/AppRedis';

@Config()
export class AppConfig extends ConfigService {
  @Inject(AppRedis)
  private redis: AppRedis;

  public transport() {
    return {
      microservice: new RedisMicroserviceTransport(this.redis, {
        serviceName: 'order-service',
      }),
    };
  }
}
```

URL, credentials and TLS now live in exactly one place. Config classes are prepared after user components are initialized, so the injected service is already connected by the time `transport()` runs.

::: tip The same works for Kafka
[`KafkaMicroserviceTransport`](/docs/packages/kafka#reusing-your-kafka-service) accepts an `AsenaKafkaService` in the same position.
:::

### How It Works

| Purpose | Redis Key | Mechanism |
|---|---|---|
| Events | `asena:ms:evt` (stream) | `XADD` + one consumer group per service; wildcard patterns matched locally; at-least-once with ACK |
| Requests | `asena:ms:req:<pattern>` (stream per pattern) | Consumer group distributes each request to exactly one replica |
| Replies | `asena:ms:reply:<instanceId>` (pub/sub) | Caller is alive and waiting — persistence unnecessary |
| Dead letters | `asena:ms:dlq` (stream) | Poison events after `maxRetries`, with provenance fields |

A background sweep (`XPENDING` + `XCLAIM`) rescues entries from crashed replicas, counts delivery attempts and moves poison events to the DLQ. **RPC errors are final** — the caller receives an `ok:false` reply and the entry is ACKed; only event handlers are retried.

### Options

| Option | Default | Description |
|---|---|---|
| `serviceName` | — (required) | Consumer group identity shared by replicas |
| `streamPrefix` | `'asena:ms'` | Key prefix for streams/channels |
| `requestTimeout` | `30000` | Default `send()` reply timeout (ms) |
| `maxRetries` | `3` | Event delivery attempts before DLQ (events only) |
| `claimIdleMs` | `60000` | Idle time before the sweep reclaims a pending entry — handler duration must stay below this |
| `maxStreamLength` | `100000` | `XADD MAXLEN ~` trim — bounds memory AND offline tolerance |
| `blockMs` | `5000` | `XREADGROUP BLOCK` duration |
| `count` | `16` | Max entries fetched per read |
| `maxInFlight` | `32` | Concurrent handler limit (backpressure) |
| `handlerTimeout` | `min(30000, claimIdleMs)` | Per-handler execution timeout — explicit values above `claimIdleMs` throw at construction; on timeout the dispatch is rejected but the handler keeps running |
| `drainTimeout` | `10000` | Graceful drain window on shutdown |
| `commandTimeout` | `10000` | Watchdog bound for publisher commands (`XADD`, `XACK`, `XCLAIM`, ...) — a command outliving it means the connection died mid-flight, so the connection is discarded and replaced |

### Delivery Guarantees

- **Events: at-least-once.** Messages survive restarts and deploys (within the `maxStreamLength` trim window). Duplicate delivery is possible — [write idempotent handlers](/docs/concepts/microservices#idempotent-handlers).
- **RPC: at-most-once per attempt.** Handler errors are final; retrying is the caller's decision.
- **Replies are not durable.** A reply is a plain `PUBLISH` on the caller's reply channel and the request entry is ACKed either way — Redis pub/sub has no replay, so a reply published while the caller has no live subscription on that channel is **dropped and never redelivered**. The caller sees a `TIMEOUT`. This is the one place where the transport is deliberately lossy; see [Reply loss across an outage](#reply-loss-across-an-outage) for exactly when it bites.
- **Readiness means "this instance can complete a `send()`", not "a socket is open".** `isConnected` requires the publisher connection **and** a reply subscription Redis is actually serving — the socket open *and* its `SUBSCRIBE` acknowledged since the last reconnect. Those are different facts: Bun's `RedisClient` reconnects on its own but does not restore subscriptions, so the replay costs a further round trip after the socket reports open, and the publisher is typically back before it finishes. Expect an instance to stay `503` a little past its reconnect; that is the honest signal, and it is what keeps a load balancer from releasing traffic at a pod whose replies are still being dropped.
- **Reconnect:** on connection loss the transport reports `isConnected: false`, retries with capped backoff, and continues where it left off — Streams hold the messages meanwhile. If the consumer group itself was lost (Redis restart without persistence, `FLUSHALL`), the transport re-creates it automatically from the beginning of the stream, so surviving entries are replayed — but data already trimmed or flushed from the stream is gone.
- **Connection poisoning defense:** Bun's `RedisClient` loses in-flight commands when a socket dies and afterwards resolves replies against the wrong promises. The transport guards both of its command connections against this — the blocking consumer via a wedge watchdog, the publisher via connection-loss detection plus the `commandTimeout` bound — and replaces a poisoned connection with a fresh one. The publisher is always a transport-owned duplicate, so a shared `AsenaRedisService` client is never touched.
- **Retry latency is sweep-driven, not immediate.** A failed event is redelivered by the sweep once its idle time exceeds `claimIdleMs` — with defaults the first retry lands after ~60–90s and a poison message reaches the DLQ after `maxRetries` sweep cycles (minutes, not seconds). Coming from BullMQ/NestJS-style immediate retries, plan for this or lower `claimIdleMs`.
- **No ordering guarantee.** Entries within a read batch are dispatched in parallel; consumers must not rely on event order.

### Reply Loss Across an Outage

Readiness is honest about the reply channel, but it does **not** make the reply channel durable. A reply is lost whenever it is published at a moment when the caller has no subscription on its reply channel:

| Situation | Outcome |
|---|---|
| `send()` in flight when the connection drops | **Lost.** The responder publishes into an empty channel and ACKs the request; the caller gets a `TIMEOUT` after `requestTimeout`. |
| `send()` issued while the instance reports `503` | Your own choice — the endpoint told you it could not serve. |
| `send()` issued after the instance reports `200` | Delivered. This is what readiness now guarantees; before it did not. |

So an RPC that spans a Redis outage must be treated as **retryable, not reliable**. Make handlers idempotent and retry the `TIMEOUT` at the caller, or use `emit()` (Streams, at-least-once) where losing the call is unacceptable.

Two narrower residuals are worth knowing about:

- Readiness is driven by connection events, so a health check that lands between the socket being marked open and the connect event being dispatched can read `200` for at most one event-loop turn.
- A **custom** `RedisClientAdapter` that implements `onConnected` but neither `onResubscribed` nor subscription restoration of its own is taken at its word on connect. Both built-in adapters (`BunRedisAdapter`, `NodeRedisAdapter`) report honestly.

::: warning Liveness must be more forgiving than readiness
`isConnected` feeds Asena's health endpoint: `503` now means "the publisher is down **or** this instance's reply channel is not being served", i.e. a `send()` issued right now cannot complete. Wire it into your orchestrator's **readiness** probe. Because an instance stays `503` until its reply subscription is acknowledged — not merely until its socket reconnects — a liveness probe sharing the same thresholds will restart pods that were about to recover on their own.
:::

::: info Durable replies are not in 0.9.0
Moving replies onto a Stream would close the loss entirely, at the cost of a per-request write and trim. It is deliberately deferred; the table above is the current contract.
:::

## Best Practices

### 1. Name Your Redis Services

```typescript
// ✅ Good: Named service for clear IoC registration
@Redis({
  config: { url: 'redis://localhost:6379' },
  name: 'AppRedis',
})
export class AppRedis extends AsenaRedisService {}

// ❌ Bad: Unnamed service (defaults to class name, but less explicit)
@Redis({ config: { url: 'redis://localhost:6379' } })
export class AppRedis extends AsenaRedisService {}
```

### 2. Cache with Decorators

```typescript
// ✅ Good: The policy is on the method, the method is only the lookup
@Cacheable({ prefix: 'user', ttl: 60, key: (id: string) => id })
async findById(id: string) {
  return this.users.findById(id);
}

// ❌ Bad: Every method repeats the same steps by hand
async findById(id: string) {
  const cached = await this.redis.get(`user:${id}`);
  if (cached) return JSON.parse(cached);

  const user = await this.users.findById(id);
  await this.redis.set(`user:${id}`, JSON.stringify(user), 60);
  return user;
}
```

See [Caching Decorators](#caching-decorators), including the [time limit](#time-limit) that keeps a
cached call from waiting on Redis during an outage.

### 3. Health Checks

```typescript
// ✅ Good: Use testConnection() in health endpoints
@Get('/health')
async health(context: Context) {
  const redisOk = await this.redis.testConnection();
  return context.send({ redis: redisOk ? 'up' : 'down' });
}
```

The probe is bounded: an unreachable Redis makes `testConnection()` return `false` within
`ping()`'s timeout (1000 ms by default) instead of leaving the request hanging on a queued
command.

::: warning `testConnection()` is not a microservice readiness check
It `PING`s the cache client and says nothing about whether this instance's **reply channel** is being served, which is what decides whether a `send()` can complete. For an instance running `RedisMicroserviceTransport`, the readiness signal is the transport's `isConnected` (already wired into Asena's health endpoint) — see [Delivery Guarantees](#delivery-guarantees).
:::

## Related

- [WebSocket](/docs/concepts/websocket) - WebSocket implementation guide
- [Microservices](/docs/concepts/microservices) - Microservice messaging concepts and delivery semantics
- [Configuration](/docs/guides/configuration) - Server configuration with `transport()`
- [Services](/docs/concepts/services) - Service layer architecture
- [Dependency Injection](/docs/concepts/dependency-injection) - IoC container
- [Kafka](/docs/packages/kafka) - The same transport SPI on a different broker
