# Add Caching to a Vapor App

Yes. An agent caches a Vapor app's list route with the built-in Cache API, clears it on every write, proves it with Swift Testing and opens a PR noting Redis.

[Run this on Rush](https://cloud.getrush.ai/run/add-caching/vapor/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the app before it caches anything. In a project generated from vapor/template with Fluent, Package.swift is `swift-tools-version:6.3`, depends on vapor from 4.121.4, fluent from 4.13.0, a Fluent driver (Postgres 2.12.0, MySQL 4.8.0 or SQLite 4.9.0, as manifest.yml offers) and swift-nio from 2.101.0, and turns on upcoming features such as `ExistentialAny` and `MemberImportVisibility`. Sources/App/configure.swift picks the driver from DATABASE_HOST and the other variables, or `db.sqlite` for SQLite, adds `CreateTodo` to the migrations and calls `routes(app)`; it configures no cache. Controllers/TodoController.swift serves `GET /todos` with `Todo.query(on: req.db).all()` mapped through `toDTO()`, `POST /todos` decoding a TodoDTO and saving it, and `DELETE /todos/:todoID`. Models/Todo.swift has a UUID id and a title; DTOs/TodoDTO.swift carries both as optionals. Tests/AppTests/AppTests.swift is a Swift Testing suite marked `.serialized` whose `withApp` helper makes an Application in `.testing`, runs `configure`, auto-migrates, runs the test and reverts, with cases for the hello route and for listing, creating and deleting todos through `app.testing()`.

The cache is Vapor's own. configure.swift gains `app.caches.use(.memory)`, and in TodoController the list handler asks `req.cache.get` for the array of DTOs under one key, answers from it when present, and otherwise queries Fluent, stores the result with an expiry through `req.cache.set` and returns it. `POST` and `DELETE` call `req.cache.delete` on that key after their write, so the next list reflects the change; the not-found branch of delete writes nothing and so clears nothing. The key and the expiry are constants at the top of the controller where a reviewer finds them. Redis is not added: the description explains that `app.caches.use(.redis)` from the vapor/redis package is the one-line swap for a deployment with several instances, where one in-memory cache per process would serve different lists, and leaves that choice to the reader.

Tests go into AppTests.swift in the existing style. A list fetched twice returns the same todos and the second answer comes from the cache, shown by creating a row directly on `app.db` between the two requests and seeing it absent from the second; a POST through the route then makes a third list include it; a DELETE through the route removes it from the next list; and a list requested after the expiry, with a short expiry set for the test, sees the direct insert. The `.serialized` suite and the per-test migrate and revert keep the cache and the database aligned between cases, and a fresh Application per test gets a fresh memory cache. Then `swift build` and `swift test`, the commands TEMPLATE_README.md gives, and `docker compose build` from docker-compose.yml, which the template's workflow runs for every driver and Leaf combination, so the Dockerfile's static release build still succeeds with the change.

The agent also runs the server with `swift run` and sends the requests by hand with curl: two GETs, a POST, a GET, a DELETE and a GET, so the pull request can show the list changing only after writes and the second GET answered without a query, read from the request log at the debug level docker-compose.yml sets.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add caching to this Vapor app. Read Package.swift, Sources/App/configure.swift, routes.swift and entrypoint.swift, Controllers/TodoController.swift, Models/Todo.swift, DTOs/TodoDTO.swift, Migrations/CreateTodo.swift, Tests/AppTests/AppTests.swift, Dockerfile and docker-compose.yml first. Configure Vapor's built-in in-memory cache in configure.swift and make the todo list handler read the DTO array from req.cache under one key, fall back to the Fluent query and store the result with an expiry, and clear the key after every successful create and delete. Keep the key and expiry as named constants. Do not add Redis, but explain in the pull request the one-line swap to the Redis driver for several instances. Add Swift Testing cases in the existing suite's style that prove the second list is served from the cache by inserting directly on app.db between two requests, that create and delete through the routes invalidate it, and that the entry expires. Run swift build, swift test and docker compose build, start the server and send a GET, GET, POST, GET, DELETE, GET sequence with curl, and open a pull request that quotes the test output and the curl responses.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch that changes Sources/App/configure.swift, Sources/App/Controllers/TodoController.swift and Tests/AppTests/AppTests.swift. Package.swift is untouched, because the Cache API ships with Vapor, and the Dockerfile and compose file still build.

The description names the key and the expiry, quotes the `swift test` run with the new cases among the existing todo tests, and shows the six curl responses from the sandbox with the moment the list changes marked, so a reviewer can see the cache serve a stale list only between the direct insert and the expiry, never after a write through the API.

Before merging, a reviewer sets the expiry for production, decides whether the key must become per user once the app gains authentication, and whether to move to Redis now rather than when a second instance appears. Each is a line or two, and a follow-up on the same session changes it.

## Run it on every Vapor route querying the database on every request

This is a change to start from the terminal and pick up later: one `POST /o/{org}/sessions` with this prompt and the repository in `resources`, and the run reads the controller, adds the cache, writes the tests and opens the pull request without anyone watching. The sandbox parks with its disk when the turn ends, so `switch to the Redis driver` as a follow-up wakes it with the .build directory and the branch intact, and the Swift build does not start over.

A team with several Vapor services sends the same body once per repository, one run each, and each run reads that service's own controllers. Give the API key a `webhook_url` and Rush posts `run.completed` or `run.failed` with the `session_url` when each turn ends, so the pull request links collect in one channel. Send a `request_id` with each body so a retried POST returns the run it already started.

## Why run it on Rush?

A cache is only as good as its invalidation, and the invalidation is only shown by a test that writes behind the cache's back and one that writes through the API. The agent writes both in the repository's own Swift Testing style, runs them with the rest of the suite in its sandbox, and the pull request carries the output rather than a claim that the key is cleared.

A Swift release build is slow, and the record keeps it: the transcript shows the build, the test run, the compose build and the curl sequence, so a reviewer who wants to know whether the second GET really skipped the query reads the request log the agent captured. The sandbox parks with .build on disk, so a follow-up compiles only what changed.

## Frequently asked questions

### Why not Redis from the start?

Because the template runs as one process and Vapor's in-memory cache needs no service, no secret and no package. The pull request shows the one-line swap to app.caches.use(.redis) with the vapor/redis package for the day a second instance appears.

### What happens with several instances?

Each process has its own memory cache, so a write on one instance clears only that instance's key and the others serve the old list until the expiry. That is the moment to move to the Redis driver, which the tests do not need to change for.

### Does the API change?

No. The routes, the DTOs and the status codes are the same. A client can see a stale list only when a row was written outside the API and only until the expiry; after its own create or delete the next list is fresh.

### How do the tests know the second list came from the cache?

They insert a todo directly on app.db between two GETs. The second GET does not show it, which it would if the handler had queried; a GET after the expiry, or after a POST through the route, does.

### Does it work with SQLite, MySQL and Postgres?

Yes. The cache sits above Fluent and never touches the driver, so the same change applies whichever option the project was generated with, and the compose build runs the same way.

## More Vapor jobs

- [Add CORS to a Vapor Server](https://getrush.ai/run/add-cors/vapor/)
- [Add Test Coverage to CI for a Vapor App](https://getrush.ai/run/add-coverage-to-ci/vapor/)
- [Add a Scheduled Job to a Vapor App](https://getrush.ai/run/add-cron-jobs/vapor/)

## The same job on other stacks

- [Add Caching to a Flask App](https://getrush.ai/run/add-caching/flask/)
- [Add Response Caching to a Hono API](https://getrush.ai/run/add-caching/hono/)
- [Add HTTP Caching to a Ktor API](https://getrush.ai/run/add-caching/ktor/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
