chat-room

작성자: rivet-dev

Rivet Actors로 실시간 채팅방 백엔드 구축: 방마다 하나의 액터, SQLite 기반 메시지 기록, 모든 연결된 클라이언트에 WebSocket 브로드캐스트.

npx skills add https://github.com/rivet-dev/skills --skill chat-room

Chat Room

IMPORTANT: Before doing anything, you MUST read BASE_SKILL.md in this skill's directory. It contains essential guidance on debugging, error handling, state management, deployment, and project setup. Those rules and patterns apply to all RivetKit work. Everything below assumes you have already read and understood it.

Working Examples

If you need a reference implementation, read the raw working example code in these templates:

Patterns for building a chat room backend with RivetKit: room-scoped actors, persistent message history, and realtime delivery over WebSocket connections.

Starter Code

Start with the working example on GitHub and adapt it. The backend is a single chatRoom actor; the frontend is a React app using @rivetkit/react (see the React quickstart).

TopicSummary
Room modelOne chatRoom actor per room key. The frontend defaults the key to general; typing a different room name connects to a different actor.
HistorySQLite messages table created in db({ onMigrate }), read back with ORDER BY id ASC.
DeliverysendMessage inserts the row, then broadcasts a typed newMessage event to every connected client.
IdentityNone in the example. sender is a plain action argument; production should bind identity to the connection.

Room-Per-Actor Model

Each room is one Rivet Actor instance, addressed by key. The client calls useActor({ name: "chatRoom", key: [roomId] }), which gets-or-creates the actor for that room. This gives you:

  • Isolation: each room's history and connections are fully scoped to its key. Switching the room input re-keys the hook and connects to a different actor with separate history.
  • A single serialized writer: all sendMessage calls for one room run through one actor, so message ordering is consistent without locks. The SQLite AUTOINCREMENT id is the canonical order, which is why getHistory sorts by id rather than by timestamp.
  • Natural scaling: rooms spread across the cluster independently. A hot room does not slow down other rooms.

Message History Storage

This example stores history in the actor's SQLite database, not in JSON state. Pick based on history size and query needs:

ApproachUse WhenImplementation Guidance
SQLite (what this example uses)Large or long-lived history that needs ordering, caps, pagination, or searchCreate the messages table in db({ onMigrate }), insert with parameterized queries (c.db.execute("INSERT ... VALUES (?, ?, ?)", ...)), and read with ORDER BY id ASC. History survives actor sleep and scales past what you want in memory.
JSON stateSmall recent history, for example the last 50 to 100 messagesPush onto a messages array in actor state and trim to a cap on every send. Simplest option, but the whole history lives in memory and there is no query layer, so it only fits bounded recent-history use cases.

Broadcast Delivery

New messages reach connected clients through a typed event:

  • The actor declares events: { newMessage: event() }, where Message is { sender, text, timestamp }.
  • The sendMessage action builds the message with a server-side Date.now() timestamp, inserts it into the messages table, then calls c.broadcast("newMessage", message) and returns the message to the caller.
  • Each client subscribes with useEvent("newMessage", ...) and appends to its local list. The sender renders its own message through the same broadcast path as everyone else, so all clients stay on one code path.
  • History load is connection-gated: once the connection is ready, the client calls getHistory() once to render the backlog, then relies on events for everything after.

Use c.broadcast(...) for room-wide messages. For private or per-recipient payloads (such as DMs inside a room), send on the individual connection instead, which is a recommended extension beyond this example.

Typing Indicators And Presence (Extension)

The example does not implement typing indicators, presence, or join/leave handling of any kind. There is no createConnState, onConnect, or onDisconnect in the code. If you need them, add them as ephemeral connection behavior:

  • Keep it ephemeral: store the username and typing flag in per-connection state, never in SQLite or persisted actor state. Presence is derived from live connections and should disappear with them.
  • Broadcast on change only: emit a typing event when a user starts or stops typing, and a presence event from onConnect / onDisconnect, rather than polling or ticking.
  • Expire on the client: clear a typing indicator after a short client-side timeout so a dropped connection never leaves a stuck "is typing" row.

Per-User Inbox (Extension)

For offline delivery, DMs, unread counts, or notification fanout, add a userInbox[userId] actor per user. This is an extension beyond the example:

  • The room actor forwards each message to the inbox actor of every member via actor-to-actor calls, so users who are not connected to the room still accumulate messages.
  • The inbox actor owns per-user unread state and serves it when the user comes online, independent of which rooms they are in.
  • DMs become a degenerate room: either a chatRoom keyed by the sorted pair of user ids, or direct inbox-to-inbox delivery if you do not need shared history semantics.

Actors

  • Key: chatRoom[roomId]
  • Responsibility: Owns one chat room. Persists the room's message history in its SQLite database and broadcasts each new message to every connected client.
  • Actions
    • sendMessage
    • getHistory
  • Queues
    • None
  • Events
    • newMessage
  • State
    • SQLite
    • messages table: id (autoincrement primary key), sender, text, timestamp

Lifecycle

sequenceDiagram
	participant A as Client A
	participant B as Client B
	participant R as chatRoom

	A->>R: connect with key [roomId]
	Note over R: every start runs onMigrate (CREATE TABLE IF NOT EXISTS messages)
	A->>R: getHistory()
	R-->>A: Message[] ordered by id
	B->>R: connect with key [roomId]
	B->>R: getHistory()
	R-->>B: Message[] ordered by id
	A->>R: sendMessage(sender, text)
	Note over R: INSERT row with server timestamp
	R-->>A: newMessage (broadcast)
	R-->>B: newMessage (broadcast)
	A->>R: disconnect
	Note over R: history stays in SQLite for the next connection

Security Checklist

The example is intentionally minimal and skips all of the following. Add them before production:

  • Auth before join: any client can join any room by knowing its name, and sender is arbitrary client input on every call. Validate a token during connection auth, bind identity to connection state, and check room membership before serving history. Never trust a sender name passed as an action argument.
  • Message length clamps: the example accepts empty messages and has no length limit. Trim server-side, reject empty text, and clamp to a maximum length.
  • Per-connection rate limiting: rate limit sendMessage per connection to stop spam and broadcast amplification.
  • Server-side timestamps and ids: the example already does this correctly. timestamp comes from Date.now() inside the action and id from SQLite AUTOINCREMENT. Keep it that way; never accept client-supplied timestamps or ids.
  • History caps: getHistory returns every row with no limit. Add a LIMIT plus pagination, and prune or archive old rows so a long-lived room cannot grow unbounded.
  • Parameterized queries: the example already inserts with ? placeholders. Keep all user-supplied text out of SQL string interpolation.

Reference Map

Actors

Cli

Clients

Cookbook

Deploy

General

Self Hosting

rivet-dev의 다른 스킬

ai-agent
rivet-dev
지속적 메모리를 갖춘 AI 에이전트 백엔드 구축: 대화당 하나의 Rivet Actor, 대기열 메시지 처리, 실시간 이벤트로 스트리밍되는 LLM 응답.
official
ai-agent-workspace
rivet-dev
모든 AI 에이전트에게 자신만의 컴퓨터를 부여하세요: 경량 인프로세스 상에서 파일 시스템, 프로세스, 셸, 네트워킹 및 에이전트 세션을 갖춘 영구 작업 공간입니다…
official
collaborative-text-editor
rivet-dev
Yjs CRDT와 Rivet Actors를 사용하여 협업 텍스트 편집기 백엔드를 구축합니다: 문서별 액터가 동기화 및 인식 업데이트를 중계하고 스냅샷을 유지합니다.
official
cron-jobs
rivet-dev
Rivet Actors를 사용한 내구성 있는 크론 작업: schedule.after 및 schedule.at 타이머는 재시작과 충돌에도 유지되며, 반복 작업 재설정 및 멱등성 핸들러를 지원합니다.
official
live-cursors
rivet-dev
Rivet Actors를 사용한 라이브 커서 및 멀티플레이어 프레즌스: 연결별 커서 상태, 이벤트 또는 원시 WebSocket을 통한 실시간 업데이트, 스로틀링.
official
per-tenant-database
rivet-dev
멀티 테넌트 데이터 격리를 위해 테넌트당 하나의 Rivet 액터를 사용합니다. 액터 키는 테넌트 ID이므로 각 테넌트는 자체 격리된 데이터셋과 마이그레이션을 갖습니다.
official
rivetkit-client-javascript
rivet-dev
JavaScript 클라이언트로, 무상태 또는 상태 저장 연결을 통해 Rivet Actors에 연결합니다. 브라우저, Node.js 및 Bun 환경을 지원하며, 환경 변수 또는 명시적 구성을 통한 자동 엔드포인트 감지 기능을 제공합니다. 독립적인 요청을 위한 무상태 액션 호출과 실시간 이벤트 구독이 가능한 상태 저장 연결의 두 가지 상호작용 모드를 제공합니다. onRequest 또는 onWebSocket 핸들러를 구현하는 액터를 위한 저수준 HTTP 및 WebSocket 액세스를 포함하며, 복합 배열 기반...
official
rivetkit-client-react
rivet-dev
React 클라이언트로, 훅과 실시간 상태 관리를 통해 Rivet Actors에 연결합니다. createRivetKit()으로 타입이 지정된 훅을 생성하고, useActor()로 키와 선택적 매개변수를 사용하여 액터 인스턴스에 연결합니다. useEvent()로 액터 이벤트를 구독하고, connStatus와 error 상태를 통해 연결 수명 주기를 모니터링합니다. createClient()를 사용하여 상태 비저장 단일 호출, 액터 검색 메서드(get, getOrCreate, create, getForId), 그리고 저수준 HTTP/WebSocket 액세스를 수행합니다. 복합 배열 키를 지원합니다...
official