Skip to content
TypeScript
4.8 KB
Raw Blame
---
title: "Part 3: Persist Data with a Volume"
description: Mount a Fly disk into your Service with MountVolume and store files that survive deploys.
sidebar:
  order: 3
---

import Terminal from "../../../../components/Terminal.astro";
import PackageManagers from "../../../../components/PackageManagers.astro";

Your Service from [Part 2](/fly/tutorial/part-2) is stateless.
Writes to the Machine's root disk die with the Machine. In this
part you mount a Volume so files survive deploys.

:::caution[One Volume, one Machine]
A Fly Volume attaches to one Machine. Two Services cannot mount
the same disk. `count: 3` creates three independent Volumes, one
per replica.
:::

## Mount a disk into the Service

There is no standalone Volume resource. Inside the Service's constructor,
`Fly.MountVolume({ path, sizeGb })` creates a per-replica disk in
the Service's App and region:

```diff lang="typescript"
// src/api.ts
import * as Fly from "@alchemy.run/fly";
import * as Effect from "effect/Effect";
import { HttpServerRequest } from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";

export default class Api extends Fly.Service<Api>()(
  "Api",
  { main: import.meta.url, region: "iad", port: 3000 },
  Effect.gen(function* () {
+    const mount = yield* Fly.MountVolume({ path: "/data", sizeGb: 1 });

    return {
      fetch: /* ... */,
    };
  }),
) {}
```

`MountVolume` is a **binding**: at deploy time it tells the Service
"create a 1 GB Volume and put it in `config.mounts` at `/data`", and
at runtime it hands you the resolved `mount.path`.

## Provide the binding layer

Bindings declare a capability; layers implement it. Provide
`MountVolumeLive` on the Service's constructor Effect:

```diff lang="typescript"
  Effect.gen(function* () {
    const mount = yield* Fly.MountVolume({ path: "/data", sizeGb: 1 });

    return {
      fetch: /* ... */,
    };
-  }),
+  }).pipe(Effect.provide(Fly.MountVolumeLive)),
) {}
```

## Resolve FileSystem in the constructor

Yield `FileSystem` in the outer Effect. Close over it in `fetch`.
Do not yield it per request.

```diff lang="typescript"
// src/api.ts
+import * as FileSystem from "effect/FileSystem";
// ...
  Effect.gen(function* () {
    const mount = yield* Fly.MountVolume({ path: "/data", sizeGb: 1 });
+    const fs = yield* FileSystem.FileSystem;

    return {
      fetch: /* ... */,
    };
  }).pipe(Effect.provide(Fly.MountVolumeLive)),
```

## Write files with `PUT /:name`

The Volume is a directory. Use `fs` from the constructor:

```diff lang="typescript"
fetch: Effect.gen(function* () {
  const request = yield* HttpServerRequest;
  const url = new URL(request.url, "http://service");
  if (url.pathname === "/health") {
    return HttpServerResponse.json({ ok: true });
  }
+  const file = `${mount.path}${url.pathname}`;
+
+  if (request.method === "PUT") {
+    const body = yield* request.text;
+    yield* fs.writeFileString(file, body).pipe(Effect.orDie);
+    return HttpServerResponse.empty({ status: 204 });
+  }
+
  return HttpServerResponse.text("Hello from Fly!");
}),
```

## Read files with `GET /:name`

Add the read branch, turning a missing file into a 404:

```diff lang="typescript"
if (request.method === "PUT") {
  const body = yield* request.text;
  yield* fs.writeFileString(file, body).pipe(Effect.orDie);
  return HttpServerResponse.empty({ status: 204 });
}

+if (request.method === "GET") {
+  const text = yield* fs.readFileString(file).pipe(
+    Effect.catch(() => Effect.succeed(undefined)),
+  );
+  if (text === undefined) {
+    return HttpServerResponse.text("Not found", { status: 404 });
+  }
+  return HttpServerResponse.text(text);
+}

return HttpServerResponse.text("Hello from Fly!");
```

## Deploy

<PackageManagers run="alchemy deploy" />

<Terminal content={`[u]Plan[/u]: [y]1 to update[/y]

[y]~[/y] [b]Api[/b] [d](Fly.Service)[/d]

Proceed?
◉ Yes ○ No
[g]✓[/g] [b]Api[/b] [d](Fly.Service)[/d] [y]updated[/y]`} />

During the Service's deploy, Alchemy creates the Volume and writes
it into the Machine's `config.mounts` at `/data`. The disk lives in
the Service's region (`iad`).

## Try it out

```sh
# Store a file on the Volume
curl -X PUT https://myapp-api-dev-a1b2c3d4.fly.dev/hello.txt -d 'Hello, Volume!'

# Read it back
curl https://myapp-api-dev-a1b2c3d4.fly.dev/hello.txt
# → Hello, Volume!
```

Ship another code change and deploy — the file is still there. If
the Machine is replaced, the Volume re-attaches on the next deploy.

## Recap

You now have:

- A 1 GB Volume in `iad` mounted at `/data` on the API Machine
- A Service reading and writing it through Effect's `FileSystem` —
  no SDK, just files
- Data that outlives deploys and Machine replacement

In [Part 4](/fly/tutorial/part-4), you'll read a secret from `.env`
in the Service, then tear the stack down.