This page shows how Rindle fits into an application at the simplest level: plain HTTP endpoints on your server, and one stream per client. Client libraries and frameworks usually build their own conventions on top of this structure, for example React.
Rindle fits into your architecture very similarly to any traditional database. Reads and writes are mediated by your server, which enforces business logic and permissions. Untrusted clients do not have direct access to read or write data in Rindle.
The only thing different about Rindle is that query results don’t come back on the request that made the query. Instead, queries are done by adding subscriptions, and all subscription results flow back to the client over one long-lived WebSocket.
How It Works
- Get a stream token. The client calls an endpoint on your server, which checks the user as
normal and calls Rindle’s
/db/stream-auth. The returned stream token must be sent with all of the client’s subscribe and stream calls to Rindle. To avoid the extra round trip, you can call/db/stream-authon the server and embed the resulting stream token into the page using SSR. - Open a stream. The client opens a WebSocket to
/db/streamon Rindle with the stream token. Periodically, the client calls your endpoint again to get a fresh stream token from/db/stream-auth, then sends this stream token upstream on the socket to extend its expiry. Without this extension, Rindle closes the stream after 5 minutes by default. Because only your server can get stream tokens, users who lose access to data get disconnected quickly. Use/db/stream-deauthto disconnect a user immediately. - Subscribe to queries. The client calls APIs on your server. Your server authenticates the
user as normal, then calls Rindle’s
/db/subscribeto add or remove subscriptions for that client. The results arrive on the stream, and every subscription updates together, in one transaction. - Write data. The client calls your server’s APIs like any other web app; your
server authenticates the user and calls Rindle’s
/db/execute. Every subscription the write affects updates on the stream atomically, for every user who can see it. Note there is nothing special about these writes. Any change to the Rindle database from any source updates every subscription it affects.
Server Setup
Connect to Rindle using its URL and API token:
# No connection to set up. Every request to $RINDLE_URL carries:
Authorization: Bearer $RINDLE_API_TOKENimport { createClient } from "@rindle/api";
const db = createClient({
url: process.env.RINDLE_URL,
apiToken: process.env.RINDLE_API_TOKEN,
});In development (with rindle up) the api token isn’t needed.
A Rindle http connection is not expensive. You can create one per route, or share one globally. Whatever you like. Note that the stream API does hold a WebSocket open, but servers don’t typically call that.
Stream Auth
Add an endpoint that checks the user and gets a stream token for that client from Rindle:
POST $RINDLE_URL/db/stream-auth
Authorization: Bearer $RINDLE_API_TOKEN
Rindle-Client: c_7f3k2q
Rindle-User: user_42
HTTP/1.1 200 OK
Content-Type: application/json
{ "streamToken": "eyJjIjoiY183ZjNrMnEi…" }// POST /api/rindle/auth
export async function POST(request: Request) {
const user = await getUser(request); // your own auth
if (!user) return new Response("Unauthorized", { status: 401 });
const { clientID, streamToken } = await request.json();
const result = await db.authorizeStream({
clientID,
userID: user.id,
streamToken,
});
return Response.json(result);
}Return the stream token to the client. The client calls this endpoint whenever it needs a new stream
token: before its first subscribe and stream, and every few minutes to keep the stream open.
streamToken is the client’s previous stream token, once it has one.
The first call is a round trip before the page can subscribe or open its stream. To avoid it, call
authorizeStream while server-rendering the page and put the stream token in the HTML.
Reads
Clients read data by posting to an ordinary endpoint. The endpoint authenticates the user as normal, then picks the SQL to subscribe to:
POST $RINDLE_URL/db/subscribe
Authorization: Bearer $RINDLE_API_TOKEN
Rindle-Client: c_7f3k2q
Rindle-User: user_42
Rindle-Stream-Token: eyJjIjoiY183ZjNrMnEi…
Content-Type: application/json
{
"ops": [
{
"op": "add",
"id": 7,
"sql":
"SELECT id, title FROM note WHERE owner_id = ? ORDER BY id",
"params": ["user_42"]
}
]
}
HTTP/1.1 200 OK
Content-Type: application/json
{ "ops": [{ "id": 7, "status": "ok" }] }// POST /api/note/list
export async function POST(request: Request) {
const user = await getUser(request); // your own auth
if (!user) return new Response("Unauthorized", { status: 401 });
const { clientID, subscriptionID, streamToken } = await request.json();
// See also unsubscribe() and subscribeOps()
const result = await db.subscribe({
clientID,
subscriptionID,
userID: user.id,
streamToken,
sql: "SELECT id, title FROM note WHERE owner_id = ? ORDER BY id",
params: [user.id],
});
return Response.json(result);
}clientIDidentifies the client we’re adding the subscription to. Subscriptions are owned by clients, not streams because streams are short-lived. When one stream ends, the client creates a new one and picks up without gaps.subscriptionIDis a per-client integer chosen by the client.userIDis optional. When given, Rindle ties the client to that user: a call naming the client with a different user is refused, and your server can disconnect all of a user’s clients at once with/db/stream-deauth.streamTokenis the client’s latest stream token. Rindle uses it to reach the server that holds the client’s subscriptions.
Writes
Writes are ordinary endpoints too. Authenticate the user, then run SQL against Rindle as normal:
POST $RINDLE_URL/db/execute
Authorization: Bearer $RINDLE_API_TOKEN
Content-Type: application/json
{
"statement": {
"sql": "INSERT INTO note (id, owner_id, title) VALUES (?, ?, ?)",
"args": ["n_9d2f", "user_42", "Groceries"]
}
}
HTTP/1.1 200 OK
Content-Type: application/json
{ "result": { "rows_affected": 1, … }, … }// POST /api/note/create
export async function POST(request: Request) {
const user = await getUser(request); // your own auth
if (!user) return new Response("Unauthorized", { status: 401 });
const { title } = await request.json();
// Your app mints the key: AUTOINCREMENT is not supported yet.
await db.execute({
sql: "INSERT INTO note (id, owner_id, title) VALUES (?, ?, ?)",
params: [crypto.randomUUID(), user.id, title],
});
return new Response(null, { status: 204 });
}Every matching subscription is automatically updated, and changes are sent to the affected clients’ streams.
Permissions
You already know how to implement permissions – it’s just your API server picking the SQL for a query. There is no separate permission system, and no need for one. Your endpoint uses ordinary business logic to decide which query to run, or to refuse one:
// POST /api/note/list
const { sql, params } = user.isAdmin
? { sql: "SELECT id, title FROM note ORDER BY id", params: [] }
: {
sql: "SELECT id, title FROM note WHERE owner_id = ? ORDER BY id",
params: [user.id],
};
const result = await db.subscribe({
clientID,
subscriptionID,
userID: user.id,
streamToken,
sql,
params,
});
return Response.json(result);Permission Examples
| Rule | SQL |
|---|---|
| Only your own rows | WHERE owner_id = ? |
| Rows shared with you | OR EXISTS (SELECT 1 FROM share WHERE share.note_id = note.id AND share.user_id = ?) |
| Rows in your teams | WHERE EXISTS (SELECT 1 FROM member WHERE member.team_id = doc.team_id AND member.user_id = ?) |
| Hide a column | Select only the columns this user may see: SELECT id, title FROM …, not SELECT *. Only the selected columns reach the browser. |
| Different rules per role | Pick a different query in your endpoint: if (user.isAdmin) … |
Always pass the user’s id as a parameter from your server. Never take it from the request body or URL.
Permissions Are Live
Note that because permissions in Rindle are based on live queries, the resulting permission
logic is also live. When a note is unshared, it disappears from the other user’s open page right away, because their query no longer matches it.
The same holds for anything the rule can see: team membership, a role column, an archived flag.
Some rules live outside your data: a user logs out, gets banned, or has a role your auth provider holds. For those, end the user’s streams:
await db.deauthorizeStream({ userID: user.id });That ends every stream for that user, in every tab (Rindle’s /db/stream-deauth). Their
clients ask your auth endpoint for a new stream token, your server checks them again, and anything
they are no longer allowed to see stays gone. db.deauthorizeStream({ userID, clientID }) ends
one client’s stream.