Upstash Documentation

History

2 min read

Message history allows you to retrieve past events and replay them to clients on connection. This is useful for making sure clients always have the latest state.

Overview#

All Upstash Realtime messages are automatically stored in Redis Streams. This way, messages are always delivered correctly, even after reconnects or network interruptions.

Clients can fetch past events and optionally subscribe to new events.

Configuration#

lib/realtime.ts
maxLengthnumber#

Maximum number of messages to retain per channel. Example: maxLength: 100 will keep the last 100 messages in the stream and automatically remove older messages as new ones are added.

Default: "Infinite"

expireAfterSecsnumber#

How long to keep messages per channel before deleting them (in seconds). Resets every time a message is emitted to this channel.

Default: "Infinite"

Server-Side History#

Retrieve and process history on the server:

route.ts

History Options#

limitnumber#

Maximum number of messages to retrieve (capped at 1000)

Default: "1000"

startnumber#

Fetch messages after this Unix timestamp (in milliseconds)

endnumber#

Fetch messages before this Unix timestamp (in milliseconds)

route.ts

History Response#

Each history message contains:

Subscribe with History#

You can automatically replay past messages when subscribing to a channel:

route.ts

Pass history options for more control:

route.ts

Use Cases#

Chat Application

Load recent messages when a user joins a room:

Info
We recommend keeping long chat histories in a database (e.g. Redis) and only fetching the latest messages from Upstash Realtime.
page.tsx
Notification Center

Show unread notifications with history:

notifications.tsx
Live Activity Feed

Replay recent activity when users visit:

activity-feed.tsx

How It Works#

  1. When you emit an event, it's stored in a Redis Stream with a unique stream ID
  2. The stream is trimmed to maxLength if configured
  3. The stream expires after expireAfterSecs if configured
  4. History can be fetched via channel.history() on the server
  5. History is replayed in chronological order (oldest to newest)
  6. New events continue streaming right after history replay, no messages lost

Performance Considerations#

Upstash Realtime can handle extremely large histories without problems. The bottleneck is the client who needs to handle all replayed events.

At that point you should probably consider using a database like Redis or Postgres to fetch the history once, then stream new events to the client with Upstash Realtime.

Limit History Length

For high-volume channels, limit history to prevent large initial payloads.

lib/realtime.ts
Set Expiration

Expire old messages to reduce storage:

lib/realtime.ts

Next Steps#