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.
Serverless vs. traditional
The following chart summarises the differences between the two approaches.
| Traditional server | Serverless / edge |
|---|---|
| Long-lived process | Short-lived execution |
| Persistent connections | No guaranteed reuse |
| Connection pooling | Not available |
| Single region | Often multi-region |
| Warm memory | Frequent 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.
Authentication patterns
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.
If you can store pre-generated tokens can securely in environment variables or platform secrets, then using a token directly may be preferred.
Batching queries
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.
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.
When not to use serverless patterns
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.