# RPC or HttpApi?

- Published: 2026-11-23
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-16-rpc-or-httpapi/

> Part 16 of a series that builds one backend server on Node with Effect 4. The code is in [devtrillo/effect-on-the-backend](https://github.com/devtrillo/effect-on-the-backend/tree/part-16), and this part is the `part-16` tag.

[Part 5](/writing/effect-backend-5-httpapi-define-once/) said that if the only caller is your own code in another service, the choice between HttpApi and Effect's RPC is a question for later. [Part 15](/writing/effect-backend-15-logs-spans-and-metrics/) ended with a `traceparent` header crossing from this server to the mail service. So this part puts the two side by side: the same two operations, `GetUser` and `CreateUser`, served over `effect/rpc` next to the HttpApi, both calling the same `Users` and `WelcomeJobs`.

My answer up front: HttpApi stays the default. RPC is worth it when both ends are Effect, ship from the same repo, and you'd rather get errors back as classes than as status codes. The rest of this part is the evidence, including two things about RPC over HTTP that I didn't expect.

## The contract

Here's the RPC contract for what `Api.ts` declares as a group with two endpoints:

```ts title="src/UsersRpc.ts"
import { Rpc, RpcGroup, RpcMiddleware } from "effect/rpc"
import { CurrentUser, Unauthorized } from "./Auth.ts"
import { NewUser, User, UserId } from "./User.ts"
import { UserNotFound } from "./Users.ts"

// The RPC contract for the same two operations as Api.ts. No paths, no methods, no status codes:
// a tag, a payload, a success and an error. Like Api.ts, it has no handlers and no Node imports.

// The RPC twin of Authorization: reads the bearer token, provides CurrentUser, fails with Unauthorized.
export class RpcAuth extends RpcMiddleware.Service<RpcAuth, {
  provides: CurrentUser
}>()("RpcAuth", { error: Unauthorized }) {}

export class UsersRpcs extends RpcGroup.make(
  Rpc.make("GetUser", {
    payload: { id: UserId },
    success: User,
    error: UserNotFound,
  }),
  Rpc.make("CreateUser", {
    payload: NewUser,
    success: User,
  }).middleware(RpcAuth),
) {}
```

It reuses everything part 4 and part 6 built: `UserId`, `NewUser`, `User`, `UserNotFound`, `Unauthorized`. What's gone is the HTTP: no `/users/:id`, no `HttpApiSchema.status(201)`, and no `BadRequest` or `Validation` middleware, for a reason the next sections get to. `UserNotFound` still carries `httpApiStatus: 404` from part 6, and RPC ignores it. The class goes over the wire as `{ "_tag": "UserNotFound", "id": "999" }` and comes back out as the class.

`effect/rpc` is in `effect` 4.0.5 and marked `@stability unstable`, the same as `effect/http-api`. No new dependency.

## The handlers

The handlers are the same two calls as `UsersHttp` in `Http.ts`, and the middleware is part 11's `Authorization` with the token read by hand:

```ts title="src/Rpc.ts"
import { Effect, Layer, Redacted } from "effect"
import { RpcSerialization, RpcServer } from "effect/rpc"
import { CurrentUser } from "./Auth.ts"
import { Tokens } from "./Tokens.ts"
import { Users } from "./Users.ts"
import { RpcAuth, UsersRpcs } from "./UsersRpc.ts"
import { WelcomeJobs } from "./WelcomeJobs.ts"

// HTTP headers arrive in the middleware as the RPC request's headers.
export const RpcAuthLive = Layer.effect(
  RpcAuth,
  Effect.gen(function* () {
    const tokens = yield* Tokens
    return RpcAuth.of(
      Effect.fn("RpcAuth.bearer")(function* (effect, { headers }) {
        const token = (headers["authorization"] ?? "").replace(/^Bearer /, "")
        const user = yield* tokens.verify(Redacted.make(token))
        return yield* Effect.provideService(effect, CurrentUser, user)
      }),
    )
  }),
)

// The same Users and WelcomeJobs calls as UsersHttp in Http.ts.
export const UsersRpcLive = UsersRpcs.toLayer(
  Effect.gen(function* () {
    const users = yield* Users
    const jobs = yield* WelcomeJobs
    return UsersRpcs.of({
      GetUser: ({ id }) => users.find(id),
      CreateUser: (payload) =>
        users.create(payload).pipe(
          Effect.tap((user) => jobs.enqueue({ id: user.id, name: user.name, email: payload.email })),
        ),
    })
  }),
)

// Every call is a POST to /rpc on the server's existing router. Needs Users, Tokens and WelcomeJobs.
export const RpcRoutes = RpcServer.layerHttp({ group: UsersRpcs, path: "/rpc", protocol: "http" }).pipe(
  Layer.provide([UsersRpcLive, RpcAuthLive, RpcSerialization.layerJson]),
)
```

Leave out `protocol: "http"` and `layerHttp` gives you a WebSocket endpoint instead; that's its default. Plain HTTP is one POST per batch of calls, which is easier to put behind a load balancer and to curl.

`main.ts` changes shape a little. The services used to be provided to the HttpApi handlers alone. Now both sets of handlers need them, and there must be one `WelcomeJobs` worker, not two:

```ts title="src/main.ts (excerpt)"
// The Postgres services and the welcome mail worker, now used by the HttpApi and the RPC handlers.
const Services = Layer.mergeAll(Users.layer, Tokens.layer, WelcomeJobs.layer).pipe(
  Layer.provide(Mailer.layer),
  Layer.provide(FetchHttpClient.layer),
)

const ApiRoutes = HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe(
  Layer.provide(UsersHttp.pipe(Layer.provide([ValidationLive, AuthorizationLive]))),
)

// Part 16: POST /rpc sits next to the HttpApi routes. Services is provided once,
// so both share one pool of Users and Tokens and one welcome mail worker.
const Routes = Layer.mergeAll(Health, ApiRoutes, RpcRoutes, HttpApiScalar.layer(Api)).pipe(
  Layer.provide(Services),
)
```

On SIGTERM the log says `draining welcome queue` once, so it is one worker.

## The client

The RPC client is the same program as part 5's `client.ts`, call for call:

```ts title="src/rpc-client.ts"
import { Config, Effect, Layer } from "effect"
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"
import { RpcClient, RpcSerialization } from "effect/rpc"
import { UserId } from "./User.ts"
import { UsersRpcs } from "./UsersRpc.ts"

// The same calls as client.ts, over RPC. TOKEN=$(npm run -s token -- 1) node src/rpc-client.ts
const program = Effect.gen(function* () {
  const client = yield* RpcClient.make(UsersRpcs)
  const created = yield* client.CreateUser({ name: "Grace", email: "grace@example.com" })
  const found = yield* client.GetUser({ id: UserId.make(created.id) })
  const missing = yield* client
    .GetUser({ id: UserId.make("999") })
    .pipe(Effect.catchTag("UserNotFound", (error) => Effect.succeed(error.message)))
  console.log({ created, found, missing })
  yield* client.CreateUser({ name: "", email: "nobody@example.com" })
})

// One POST to /rpc per call, with the token on every request.
const Protocol = Layer.unwrap(
  Effect.gen(function* () {
    const token = yield* Config.Redacted("TOKEN")
    return RpcClient.layerProtocolHttp({
      url: "http://localhost:3000/rpc",
      transformClient: HttpClient.mapRequest(HttpClientRequest.bearerToken(token)),
    })
  }),
).pipe(Layer.provide([RpcSerialization.layerJson, FetchHttpClient.layer]))

program.pipe(Effect.scoped, Effect.provide(Protocol), Effect.runPromise).catch(console.error)
```

`client.GetUser` has the type `Effect<User, UserNotFound | RpcClientError>`, and `CreateUser` has `Unauthorized | RpcClientError`. `RpcClientError` is the transport: with the server stopped, every call fails with `RpcClientError: HttpError`, typed, so you can retry on it. The first three calls print the same thing `client.ts` prints.

The last call is where they part. `client.ts` fails with a `SchemaError` in the error channel, `Expected a value with a length of at least 1`. The RPC client throws `Error: Schema validation failed` as a defect. It builds the payload with the schema's `make` before sending, and `make` throws. Nothing reaches the server either way, but only one of the two lets you `catchTag` it.

## What's on the wire

Every RPC call is a JSON message in a POST body, and every answer is an `Exit`:

```sh
curl -X POST localhost:3000/rpc \
  -d '{"_tag":"Request","id":"2","tag":"GetUser","payload":{"id":"999"},"headers":[]}'
```

```text title="curl, one request at a time"
GetUser 1         200  {"_tag":"Exit", ... "exit":{"_tag":"Success","value":{"id":"1","name":"Ada",...}}}
GetUser 999       200  ... "exit":{"_tag":"Failure","cause":[{"_tag":"Fail","error":{"_tag":"UserNotFound","id":"999"}}]}
CreateUser        200  ... "cause":[{"_tag":"Fail","error":{"_tag":"Unauthorized"}}]      (no token)
GetUser "abc"     200  ... "cause":[{"_tag":"Die","defect":"Expected a positive integer\n  at [\"id\"]"}]
tag "Nope"        200  ... "cause":[{"_tag":"Die","defect":"Unknown request tag: Nope"}]
body "not json"   200  [{"_tag":"Defect","defect":{"name":"SyntaxError", ...}}]
```

Every one of them is a 200. The HttpApi answers the same requests with 200, 404, 401 and 400. The status code lives inside the body now, as `Success`, `Fail` or `Die`, and only an Effect client reads it.

Two of those rows are worse than they look.

## A bad payload is a defect

`GetUser` with `"abc"` comes back as `Die`, not as an error the contract declares. The server decodes each payload against the RPC's schema before it runs anything, and on failure it sends a defect with the formatted issue. There's no `BadRequest` to declare, because there's no hook like part 6's `layerSchemaErrorTransform` to turn it into one.

The decode also runs before the middleware. A blank name sent to `CreateUser` with no token comes back as `Die: Expected a value with a length of at least 1`, where the HttpApi answers 401 (part 12 has a test for that order). An unauthenticated caller gets to learn your validation rules.

And nobody hears about it. I sent five bad requests with curl (a bad id, two bad payloads, an unknown tag, broken JSON) and checked the server log and Tempo:

```text title="One bad payload, everywhere I looked"
access log   Sent HTTP response { 'http.method': 'POST', 'http.url': '/rpc', 'http.status': 200 }
Tempo        POST [server] 200 OK, 1 span, no GetUser child
other logs   nothing
```

The RPC span is never opened, because the request never gets as far as a handler. The HTTP span sees a 200. A caller sending the wrong shape for a week would show up nowhere except in its own errors. With HttpApi the same caller is a column of 400s on any dashboard.

It's one of two reasons I'd keep RPC for callers I deploy myself. The other is version skew.

**Quiz:** An Effect caller sends CreateUser with a blank name and no authorization header. What does it get back?

- Unauthorized, like the HttpApi's 401
- A defect: Expected a value with a length of at least 1
- An HTTP 400 that RpcClient turns into RpcClientError

**Answer:** A defect: Expected a value with a length of at least 1 — Over the wire the server sends Die with the formatted issue. From RpcClient it never even leaves: make throws Schema validation failed on the caller's side. Either way it isn't in the error channel.

- Not "Unauthorized, like the HttpApi's 401": That's the HttpApi order: security middleware first, then payload validation. RPC decodes the payload before any middleware runs.
- Not "An HTTP 400 that RpcClient turns into RpcClientError": RpcClientError is only for transport failures. The HTTP status is 200 for every RPC answer, including this one.

## When the two copies drift

With HttpApi, the server and its callers can drift a little and the failure has a name: an extra field gets stripped, a missing one is a 400, a moved path is a 404. With RPC, both sides compile against the same `UsersRpcs`, and the whole idea assumes they're deployed from the same commit. `src/part-16/skew.ts` runs three callers whose copy of the contract is out of date against the running server:

```text title="node src/part-16/skew.ts"
newer success schema: defect SchemaError: Missing key
renamed payload field: defect Error: Missing key
renamed procedure: defect Error: Unknown request tag: FindUser
```

All three are defects. The first is the caller rejecting the server's answer (its `User` expects a `role` the server doesn't send); the other two are the server rejecting the caller. During a rolling deploy, where old and new versions run side by side for a minute, that's what the in-between looks like. Add fields as optional first, remove them a deploy later, and don't rename procedures. HttpApi needs the same care, but it fails with a status you'd see.

## One trace from caller to Postgres

The part that worked better than I expected was tracing. I ran the client with part 15's `TelemetryLive` and a `caller` span around the program, and Tempo had one trace for the whole run:

```text title="One trace, two processes"
caller                       [internal]
  CreateUser                 [client]   rpc.method CreateUser
    POST                     [client]   200
      POST                   [server]   200   http.route /rpc
        CreateUser           [server]   rpc.method CreateUser
          RpcAuth.bearer
            Tokens.verify
            Users.create
              sql.transaction
            WelcomeJobs.enqueue
              WelcomeJobs.send
                Mailer.welcome
  GetUser                    [client]
    POST ...                            GetUser [server] → Users.find
  GetUser                    [client]   error
    POST ...                            GetUser [server] error → Users.find error
  CreateUser                 [client]   error, 0 ms
```

The RPC spans are named after the procedure and carry `rpc.system.name: effect_rpc`. `GetUser 999` marks both RPC spans as errors while the HTTP spans between them say 200, so filter on the RPC spans, not the HTTP ones. The last `CreateUser` is the blank name: 0 ms, and no POST under it.

Over HTTP the trace joins through the `traceparent` header that part 15 found `HttpClient` sending, not through RPC itself. In `RpcServer.ts` the HTTP protocol sets `supportsSpanPropagation: false`; the WebSocket, socket and worker protocols carry the trace id inside each message instead. Either way, it came out as one trace.

**Quiz:** In Tempo, how do you find the GetUser calls that failed with UserNotFound?

- Search for server spans with http.response.status_code 404
- Search for GetUser spans with an error status
- You can't; RPC over HTTP doesn't propagate spans

**Answer:** Search for GetUser spans with an error status — The RPC server span is named after the procedure and set to error when the handler fails. Calls that failed to decode won't be there, though: they never get an RPC span.

- Not "Search for server spans with http.response.status_code 404": There aren't any. Every RPC answer is a 200, so the HTTP server span is OK even when the call failed.
- Not "You can't; RPC over HTTP doesn't propagate spans": The HTTP protocol doesn't put the trace in the RPC message, but HttpClient's traceparent header joins the trace anyway.

## What RPC has that HttpApi doesn't

It isn't only a smaller contract. Four things here have no HttpApi equivalent:

- **Streams.** `Rpc.make("...", { success: User, stream: true })` returns a `Stream` to the caller. Over HTTP it needs `RpcSerialization.layerNdjson`; with `layerJson` the server collects the whole stream before it answers (`RpcServer.ts` only streams when the serialization does its own framing).
- **Batching.** Two `Request` messages in one POST body come back as two `Exit`s in one response, each with its own server span. My client sent one POST per call, since it awaited each one.
- **Other transports.** The same `UsersRpcs` runs over a WebSocket, a raw socket, stdio or a worker thread, by swapping one protocol layer on each side.
- **Errors as values.** `catchTag("UserNotFound")` on the caller, with no status code invented for it. Part 6 put `httpApiStatus: 404` on the domain class and said to map it at the edge once a second kind of caller arrived. RPC is that caller, and it turns out to need no mapping at all.

What you give up is everything outside Effect. There's no OpenAPI document and no `/docs`, a curl call needs the envelope above, and nothing that reads HTTP status codes (a load balancer's health stats, a CDN, a dashboard of 5xx rates) can tell a failed call from a good one.

## Tests

`RpcTest.makeClient` connects a client straight to the handlers, the way part 12's `HttpApiTest` does. `test/UsersRpc.test.ts` runs the real handlers and `RpcAuth` with the in-memory `Users` and the fake `Tokens` from part 12:

```ts title="test/UsersRpc.test.ts (excerpt)"
it.effect("CreateUser with Ada's token creates the user", () =>
  Effect.gen(function* () {
    const client = yield* RpcTest.makeClient(UsersRpcs)
    const user = yield* client.CreateUser(
      { name: "Grace", email: "grace@example.com" },
      { headers: { authorization: "Bearer ada-token" } },
    )
    assert.strictEqual(user.name, "Grace")
  }),
)
```

`RpcTest` skips serialization, which also means the server never decodes the payload. So the decode-before-auth test can't use it. Like part 12's raw requests, it goes through `HttpRouter.toWebHandler` with `RpcServer.layerHttp`, and asserts the 200 with the `Die` inside. `npm test` is 42 passed plus part 14's one expected fail.

## Gotchas

- **`layerHttp` defaults to WebSocket.** Without `protocol: "http"` there's no POST route at all.
- **The client's URL gets a trailing slash.** The server logged `/rpc/` for `RpcClient` calls and `/rpc` for curl. The router treats them the same (part 3), but a proxy rule matching `/rpc` exactly won't.
- **`httpApiStatus` is inert.** It's on `UserNotFound` and `Unauthorized`, and RPC doesn't read it. Harmless, but don't expect it to show up anywhere.

## Which one, then

| The caller is…                                         | Use     |
| ------------------------------------------------------ | ------- |
| a browser, a mobile app, curl, another language        | HttpApi |
| a partner or anyone you don't deploy                   | HttpApi |
| your own Effect service, shipped from the same repo    | RPC     |
| your own Effect service that needs a stream of results | RPC     |

This server's public API stays HttpApi. `/rpc` stays in the repo for the comparison, though nothing calls it yet, and I'd never let it be the only way in. If a second Effect service needs users, that's the day it earns its place.

## Run it

```sh
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-16
npm install
npm test
docker compose up -d --wait
cp .env.example .env
npm run mail
```

Then `npm start` in a second terminal and, in a third, `TOKEN=$(npm run -s token -- 1) node src/rpc-client.ts`, or `node src/part-16/skew.ts` for the drift. The repo stays on `effect` 4.0.5; 4.0.6 is out, and nothing here needed it.

The server now has two APIs, a Postgres pool, a mail worker and a collector, all on a laptop. It has never run anywhere else.

Next in the series: shipping it.

- **Part 17 — Shipping it**: An esbuild bundle in a node:24-slim image, /health and /ready probes that stay out of the logs, and the CMD line that decides whether SIGTERM ever reaches runMain.
