Skip to content

Real-time chat with an in-memory backend

Use an Arc observable query to keep a React chat room up to date without polling. This guide stores messages in the server process: joining a room delivers its current history, and sending a message updates the browsers subscribed to it.

Start with an Arc backend and a React app using the <Arc> provider. The room history is shared within one server process, not across instances, and disappears when that process restarts. Rooms and their histories stay in memory after the last browser leaves; this sample has no eviction policy.

The backend is shown in C#, Kotlin, Java, and TypeScript. Arc for TypeScript is published on npm; its feature coverage differs from the other backends. How the backends differ summarizes the per-language differences this guide explains.

Chat/
├── ChatRoom.cs ← ChatRoom state holder + ChatService singleton
├── ChatRoomPage.cs ← ChatMessage read model + SendMessage command
└── ChatRoomPage.tsx ← React component

This is the C# layout. Kotlin and TypeScript keep the same two backend files as .kt or .ts. Java puts each public type in its own file in the same folder.

A ChatRoom keeps its message history in a source that subscribers can observe. That source also holds the current value, so joining mid-conversation does not need a separate history request. ChatService creates rooms by name and returns the same room on later requests.

ChatMessage is the read model, the data the frontend displays. Its ForRoom query exposes the room’s history to Arc. The SendMessage command changes that history: its handler appends a message, and the room publishes a new list to its subscribers.

using System.Collections.Concurrent;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Cratis.Arc.Commands.ModelBound;
using Cratis.Arc.Queries.ModelBound;
using Cratis.Concepts;
namespace MyApp.Chat;
// Chat/ChatRoom.cs
public class ChatRoom
{
readonly object _lock = new();
readonly List<ChatMessage> _history = [];
// Holds the room's full history and hands it to every new subscriber.
public BehaviorSubject<IEnumerable<ChatMessage>> Messages { get; } = new([]);
public void Send(string user, string message)
{
lock (_lock)
{
_history.Add(new ChatMessage(ChatMessageId.New(), user, DateTimeOffset.UtcNow, message));
Messages.OnNext([.. _history]);
}
}
}
// Register as a singleton: builder.Services.AddSingleton<ChatService>();
public class ChatService
{
readonly ConcurrentDictionary<string, ChatRoom> _rooms = new();
public ChatRoom GetChatRoom(string name) => _rooms.GetOrAdd(name, _ => new ChatRoom());
}
// Chat/ChatRoomPage.cs
public record ChatMessageId(Guid Value) : ConceptAs<Guid>(Value)
{
public static ChatMessageId New() => new(Guid.NewGuid());
}
[ReadModel]
public record ChatMessage(ChatMessageId Id, string User, DateTimeOffset SentAt, string Message)
{
public static ISubject<IEnumerable<ChatMessage>> ForRoom(string roomName, ChatService chatService)
{
var room = chatService.GetChatRoom(roomName);
// A relay per subscriber, seeded with the room's current history. It follows the room only
// while Arc is subscribed: Observable.Using ends the room subscription when the client leaves.
var relay = new BehaviorSubject<IEnumerable<ChatMessage>>(room.Messages.Value);
return Subject.Create<IEnumerable<ChatMessage>>(relay, Observable.Using(() => room.Messages.Subscribe(relay), _ => relay));
}
}
[Command]
public record SendMessage(string RoomName, string User, string Message)
{
public void Handle(ChatService chatService) => chatService.GetChatRoom(RoomName).Send(User, Message);
}

View C# snippet source on GitHub

Each backend uses a source that supplies the current history to a new subscriber:

  • C#: a BehaviorSubject<IEnumerable<ChatMessage>> from System.Reactive.
  • Kotlin: a MutableStateFlow<List<ChatMessage>>, returned from the query as a Flow.
  • Java: Arc’s ObservableState<List<ChatMessage>>, returned as a Flow.Publisher.
  • TypeScript: an RxJS BehaviorSubject<ChatMessage[]>.

Because the source has a current value, every new subscription starts from the room’s history. Arc for Kotlin, Java and TypeScript also answers a one-off GET of the query from that value instead of reporting that no result is ready yet.

Send appends the message and publishes a copy of the complete list. Sending the whole list keeps the backend straightforward; Arc sends each subscriber only what changed (see Step 2). The C#, Kotlin and Java rooms serialize concurrent sends, so two messages sent at once both end up in the history. TypeScript runs one handler at a time on its event loop.

The query’s return contract differs by backend:

  • C# creates a relay BehaviorSubject for each subscriber, seeded with the room’s current history. Observable.Using subscribes the relay to the room when Arc subscribes to the query and disposes that subscription when the client leaves, so relays do not pile up on the room. With direct mode (queryDirectMode on <Arc>), when Arc for C# fails to deliver to a WebSocket subscriber, it calls OnError on the subject the query returned, so the relay keeps one subscriber’s failure away from the shared room. The default multiplexed connection reports a failed subscription to the client instead.
  • Kotlin, Java and TypeScript return the room’s source directly. Arc subscribes to it and unsubscribes when the client leaves; it never publishes into it.

The query has two kinds of parameters. roomName is a query argument; ChatService comes from the application’s services. C# resolves a parameter from dependency injection when its type is a registered service, so ChatService must be registered. Kotlin and Java mark the service parameter @FromServices, and TypeScript lists argument('roomName', String) and service(ChatService) in @query.

Register the chat service as a single instance, or each request would see its own rooms:

  • C#: register it with builder.Services.AddSingleton<ChatService>(); in Program.cs.
  • Kotlin and Java: @Component makes it a Spring singleton.
  • TypeScript: @singleton() registers it when the application discovers the module.

ChatMessageId gives every message an Id. Arc uses a property named Id (in any case) to compute what changed between two emissions, as the next step explains.

The Kotlin and Java query and command are marked @AllowAnonymous because Arc on the JVM requires an authenticated caller by default; the C# and TypeScript versions have no authorization rules.

Build the backend to generate the TypeScript proxies before writing the frontend. For C#, dotnet build runs the Arc proxy generator; the other backends use their own proxy generation commands and paths. Each produces:

  • ChatMessage.ts — the TypeScript model type
  • ForRoom.ts — the observable query proxy with use() and when() hooks
  • SendMessage.ts — the command proxy with a use() hook

The message id is a Guid in every backend’s proxy. The frontend below only turns it into a string, so it works with any backend.

Arc observable queries use delta mode by default. An emission is a value published by the room; here, each value is a complete history. Arc compares those values so it can send a smaller update over the network.

Emission What is sent
First The complete collection — the room’s full history as the initial payload
Subsequent A ChangeSet with only the added, replaced, and removed items

The use() hook applies each ChangeSet transparently. messagesResult.data always holds the full current collection — the React component never sees raw deltas.

The server compares each emission with the previous one it sent to that subscriber, matching items by their Id. A new Id is added, a missing Id is removed, and an Id whose content changed is replaced. In this append-only sample, a single new message produces one item in added. If a subscriber observes several new messages in one update, they appear together in added.

The Id matters. Without an Id property, Arc for C# sends the full collection on every emission and logs a warning, and Arc for Kotlin, Java and TypeScript compare items by their JSON instead, which cannot report a replaced item.

The server still copies and compares the growing list. The incremental pushes guide explores a backend that emits only new messages after the initial history, including the trade-off that creates in delta mode.

Chat/ChatRoomPage.tsx
import { useState } from 'react';
import { ForRoom } from './ForRoom';
import { SendMessage } from './SendMessage';
import type { ChatMessage } from './ChatMessage';
export const ChatRoomPage = () => {
const [roomName, setRoomName] = useState('');
const [joinedRoom, setJoinedRoom] = useState('');
const [user, setUser] = useState('');
const [messageText, setMessageText] = useState('');
const [messagesResult] = ForRoom
.when(joinedRoom.length > 0)
.use({ roomName: joinedRoom });
const [sendCommand, setSendValues] = SendMessage.use();
const handleJoin = () => {
if (roomName.trim() && user.trim()) {
setJoinedRoom(roomName.trim());
}
};
const handleSend = async () => {
if (!messageText.trim()) return;
setSendValues({ roomName: joinedRoom, user, message: messageText });
await sendCommand.execute();
setMessageText('');
};
if (!joinedRoom) {
return (
<div style={{ maxWidth: 400, margin: '80px auto', display: 'flex', flexDirection: 'column', gap: 12 }}>
<h2>Join a Chat Room</h2>
<input
placeholder="Room name"
value={roomName}
onChange={e => setRoomName(e.target.value)}
/>
<input
placeholder="Your name"
value={user}
onChange={e => setUser(e.target.value)}
/>
<button
onClick={handleJoin}
disabled={!roomName.trim() || !user.trim()}
>
Join
</button>
</div>
);
}
const messages: ChatMessage[] = messagesResult.data ?? [];
return (
<div style={{ maxWidth: 600, margin: '40px auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
<h2>{joinedRoom}</h2>
<p style={{ color: '#888', margin: 0 }}>Chatting as <strong>{user}</strong></p>
<div style={{
border: '1px solid #e0e0e0',
borderRadius: 8,
height: 400,
overflowY: 'auto',
padding: 16,
display: 'flex',
flexDirection: 'column',
gap: 8,
}}>
{messages.length === 0 && (
<p style={{ color: '#aaa', alignSelf: 'center', marginTop: 'auto', marginBottom: 'auto' }}>
No messages yet. Say hello!
</p>
)}
{messages.map(msg => (
<div
key={String(msg.id)}
style={{
background: msg.user === user ? '#e8f4fd' : '#f5f5f5',
borderRadius: 8,
padding: '8px 12px',
alignSelf: msg.user === user ? 'flex-end' : 'flex-start',
maxWidth: '75%',
}}
>
<div style={{ fontSize: 12, color: '#888', marginBottom: 2 }}>
<strong>{msg.user}</strong>
{' · '}
{new Date(msg.sentAt).toLocaleTimeString()}
</div>
<div>{msg.message}</div>
</div>
))}
</div>
<div style={{ display: 'flex', gap: 8 }}>
<input
style={{ flex: 1 }}
placeholder="Type a message…"
value={messageText}
onChange={e => setMessageText(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') handleSend(); }}
/>
<button
onClick={handleSend}
disabled={!messageText.trim()}
>
Send
</button>
</div>
</div>
);
};

ForRoom.when(joinedRoom.length > 0) keeps the query disabled until the user joins. Then use({ roomName: joinedRoom }) subscribes, receives the history, and updates messagesResult.data as messages arrive. The hook handles subscription cleanup when the component unmounts; the shared room and its history remain in ChatService.

setSendValues puts the room, user, and message text on the command object. sendCommand.execute() sends the HTTP POST. The handler updates the room, so this browser receives its own message through the same subscription as everyone else.

React keys each rendered message by its stable id. String(msg.id) supplies the string key without depending on how the generated proxy represents the identifier.

Piece What it does
ChatRoom Holds the history in a source with a current value; Send publishes the full list
ChatService One instance for the application; creates and tracks rooms by name
ChatMessage query ForRoom Returns the room’s source (a per-subscriber relay in C#)
SendMessage command Sends the message to the room, which pushes to every subscriber
ChatMessageId Lets Arc match messages by Id when it computes deltas
Delta mode First push = full history; later pushes = a ChangeSet with the new message
ForRoom.ts (generated) TypeScript observable query proxy with use() and when() hooks
SendMessage.ts (generated) TypeScript command proxy with a use() hook
ChatRoomPage.tsx React component; subscribes on join, renders messagesResult.data