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
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.How long to keep messages per channel before deleting them (in seconds). Resets every
time a message is emitted to this channel.
Server-Side History
Retrieve and process history on the server:route.ts
History Options
Maximum number of messages to retrieve (capped at 1000)
Fetch messages after this Unix timestamp (in milliseconds)
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
route.ts
Use Cases
Chat Application
Chat Application
Load recent messages when a user joins a room:
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
Notification Center
Show unread notifications with history:
notifications.tsx
Live Activity Feed
Live Activity Feed
Replay recent activity when users visit:
activity-feed.tsx
How It Works
- When you emit an event, it’s stored in a Redis Stream with a unique stream ID
- The stream is trimmed to
maxLengthif configured - The stream expires after
expireAfterSecsif configured - History can be fetched via
channel.history()on the server - History is replayed in chronological order (oldest to newest)
- 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
Limit History Length
For high-volume channels, limit history to prevent large initial payloads.
lib/realtime.ts
Set Expiration
Set Expiration
Expire old messages to reduce storage:
lib/realtime.ts
Next Steps
Server-Side Usage
Stream history and subscribe to events on the server
Channels
Scope history to specific rooms or users