Explaining SvelteKit SSR streaming with graceful DB timeout
SvelteKit supports streaming SSR by returning a streamed property from load, letting the HTML shell send immediately while heavy data (like chart info) streams later. To handle DB timeouts gracefully without breaking HTML, wrap the DB call in a timed promise that catches errors and returns fallback data. In the Svelte component, use #await blocks on the streamed promise to show loading and fallback UIs. This ensures SSR flushes the shell promptly and streams data updates, showing errors inline without aborting the entire HTML response.
Kit already does two passes when you hit a route:
- It runs your
load on the server, serialises the returned data into the HTML and sends it down the wire.
- It keeps the response open and will flush additional chunks as any
{@await…} blocks settle on the server.
The bit that blocks the first flush is any await you do in load, so the trick is to keep your shell values synchronous and put anything heavy behind a promise that you don’t await up‑front.
SvelteKit gives you a streamed/defer escape hatch for this. Anything you put under that key is left unresolved for the initial render, but will be resolved server‑side later and pushed to the client.
A minimal implementation could look like this:
// src/routes/+page.server.js
import { dev } from '$app/environment';
// simple timeout wrapper for any promise‑returning DB call
const withTimeout = (promise, ms) =>
Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`DB timed out after ${ms}ms`)), ms)
)
]);
export const load = ({ locals }) => {
// this is cheap – safe to include in the shell
const meta = { title: 'Charts', description: 'Some heavy chart' };
// don't await the heavy query – return it under `streamed`
const chart = withTimeout(locals.db.getChartData(), 5_000).catch((err) => {
// swallow/log the error so it doesn't abort the response
console.error(err);
// return a sentinel value for the UI
return { failed: true, message: dev ? err.message : 'Please try again later' };
});
return {
meta,
streamed: { chart }
};
};
And the page can use an {@await} block to render progressively:
<!-- src/routes/+page.svelte -->
<script>
export let data;
</script>
<svelte:head>
<title>{data.meta.title}</title>
<meta name="description" content={data.meta.description} />
</svelte:head>
<h1>{data.meta.title}</h1>
{@await data.streamed.chart}
<p>Loading chart…</p>
{:then chartData}
{#if chartData?.failed}
<p class="error">{chartData.message}</p>
{:else}
<Chart {chartData} />
{/if}
{:catch err}
<p class="error">Sorry, we couldn’t load the chart.</p>
{/await}
When the route is requested, Kit will render up to the {@await} synchronously and flush that HTML to the client straight away. The chart promise continues running on the server. When it resolves, Kit emits a small script chunk that updates the await block; if it rejects or times out, you hit the catch/sentinel branch instead of a hard 500, so the shell never “breaks”.
If you prefer the new helper, defer() from @sveltejs/kit is equivalent to the streamed property:
import { defer } from '@sveltejs/kit';
export const load = () => ({
meta: { … },
chart: defer(withTimeout(db.getChartData(), 5000).catch(/* … */))
});
The component would then {@await data.chart …}.
By catching the timeout inside the streamed promise and returning a fallback shape, you avoid throwing from load, so the initial HTML is always delivered and hydration can complete even if the database is slow.