• Start

Concepts & Guides

Connecting from serverless & edge

Serverless and edge environments change how applications connect to databases.

Instead of long-lived processes with persistent connections, serverless and edge code runs in short-lived, stateless executions, often across multiple regions.

Some examples of environments in which this pattern is used are AWS Lambda, Vercel Functions / Edge Functions, Cloudflare Workers, and Deno Deploy.

SurrealDB works well in these environments, but it's important to use the right connection patterns.

The following chart summarises the differences between the two approaches.

Traditional serverServerless / edge
Long-lived processShort-lived execution
Persistent connectionsNo guaranteed reuse
Connection poolingNot available
Single regionOften multi-region
Warm memoryFrequent cold starts

As many serverless and edge environments don't support TCP sockets, connecting over HTTP is generally used. As no persistent connection is required, this allows you to create a new client, connect, run queries and then exit.

import { Surreal } from 'surrealdb';

const db = new Surreal();

await db.connect('https://your-instance');

await db.signin({
user: 'your-user',
pass: 'your-pass',
});

await db.use({
namespace: 'app',
database: 'prod',
});

const result = await db.query('SELECT * FROM user');

Authentication by password uses secure salted and hashed passwords that rely on algorithms that are compute-heavy and purposely take a few hundred milliseconds per attempt.

// Basic approach: authenticate per request
await db.signin({ user: '...', pass: '...' });

If you can store pre-generated tokens can securely in environment variables or platform secrets, then using a token directly may be preferred.

await db.signin({ token: 'your-token' });

The flexibility of SurrealQL allows you to batch and optimise queries, performing multiple operations inside a single request instead of multiple requests. Take this example to create and link two records that might be done over three operations, returning the first two results through an SDK to finally perform a RELATE operation at the end.

-- Request 1
CREATE person:one;

-- Request 2
CREATE person:two;

-- Request 3
RELATE person:one->likes->person:two;

This can not only be sent as a single request, but even performed over a single query that both creates and relates the records in question.

RELATE
(CREATE ONLY person:one RETURN VALUE id)
->likes->
(CREATE ONLY person:two RETURN VALUE id);

Serverless and edge connections are not always the best choice.

Consider a long-lived backend service if you need:

  • Live queries or subscriptions

  • Real-time updates over WebSockets

  • High-frequency queries from the same process

  • Persistent connection state

In these cases, a traditional backend with a persistent SurrealDB connection will be more efficient.

Was this page helpful?