# Add HTTP Caching to a Ktor API

Yes. An agent installs Ktor's CachingHeaders and ConditionalHeaders plugins, adds ETags and Cache-Control to your read endpoints, tests 304s and opens a PR.

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

## What the agent does

The agent reads the routes before it adds a plugin, because caching headers are only correct on responses whose freshness the server can state. In an API like the `postgres` sample in ktorio/ktor-samples, `build.gradle.kts` applies `io.ktor.plugin` 3.6.0 with Kotlin 2.4.20, depends on `ktor-server-core-jvm`, `ktor-server-content-negotiation-jvm`, `ktor-serialization-kotlinx-json-jvm`, `ktor-server-netty-jvm`, `ktor-server-config-yaml` and the `postgresql` JDBC driver, and has `ktor-server-test-host-jvm` for tests but no test source set. `src/main/kotlin/com/example/plugins/Routing.kt` defines `POST /articles`, `GET /articles/{id}`, `PUT /articles/{id}` and `DELETE /articles/{id}` over an `ArticleService` that runs plain JDBC statements on a single `Connection`, and `GET /articles/{id}` answers an `Article` of `title` and `body` with no `ETag`, `Last-Modified` or `Cache-Control`, so every client and every proxy refetches the full body each time.

The agent adds two Ktor plugins and the dependencies they need: `io.ktor:ktor-server-caching-headers` and `io.ktor:ktor-server-conditional-headers`, the same artifacts the `kweet` and `youkube` samples in the repository already use. In a new `Caching.kt` under `plugins` it installs `CachingHeaders` with an `options` block that returns `CacheControl.MaxAge` with a short `maxAgeSeconds` and `visibility = Private` for `application/json` responses, and `ConditionalHeaders` with a `version` block that computes an `EntityTagVersion` from the article's `id`, `title` and `body`. Because `ConditionalHeaders` needs the entity to compute the tag, the `GET /articles/{id}` handler is changed to respond with the `Article` as before while the version function hashes the serialised fields; writes are left alone, since `PUT` and `DELETE` must never be served from cache.

To make the tag stable without reading twice, the agent adds an `updated_at` column alongside `title` and `body` in the `CREATE TABLE` statement in `ArticleService.kt`, sets it on insert and update, and returns it with the read so `Last-Modified` can be set too; the `Article` model gains an optional field that `kotlinx.serialization` leaves out when null, keeping the JSON shape for existing clients. The `configureCaching()` call goes into `Application.module()` in `PostgresApplication.kt` beside `configureSerialization()`.

Tests are new to this sample, so the agent creates `src/test/kotlin` and uses `testApplication` from `ktor-server-test-host` with the real module against a Postgres it starts in the sandbox with the `user`, `password` and `articles` values from `postgres.yaml`. The cases: a `GET /articles/{id}` answers `200` with an `ETag` and a `Cache-Control` of `private, max-age=...`; the same request with `If-None-Match` set to that tag answers `304` with an empty body; a `PUT` to the article changes the tag so the old `If-None-Match` answers `200` again; and `POST /articles` carries no caching headers. It runs `./gradlew build` and `./gradlew test`, which is what the repository's `build-all.sh` runs per sample in the `Build All Samples` workflow on JDK 24.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add HTTP caching to this Ktor API and open a pull request. Read build.gradle.kts, gradle.properties, src/main/resources/application.yaml, postgres.yaml, docker-compose.yaml, src/main/kotlin/com/example/PostgresApplication.kt, plugins/Routing.kt, plugins/Serialization.kt, service/ArticleService.kt and models/Article.kt first. Add the ktor-server-caching-headers and ktor-server-conditional-headers dependencies, install CachingHeaders with a private max-age for application/json responses and ConditionalHeaders with an EntityTagVersion computed from the article's id, title and body, and add an updated_at column set on insert and update so Last-Modified can be sent; keep PUT, POST and DELETE free of caching headers and keep the JSON shape for existing clients. Create a test source set with testApplication against a Postgres you start in the sandbox using the values in postgres.yaml, and cover: 200 with ETag and Cache-Control on GET /articles/{id}, 304 with If-None-Match, a changed tag after PUT, and no caching headers on POST. Run ./gradlew build and ./gradlew test and paste the outputs in the pull request. Do not change the routes' paths or the DELETE and PUT handlers.",
  "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 with two new dependencies in `build.gradle.kts`, a `Caching.kt` plugin file, an `updated_at` column and its reads and writes in `ArticleService.kt`, an optional field on `Article`, a one-line change in `PostgresApplication.kt`, and a new `src/test/kotlin` tree. The description shows the `./gradlew test` report with the four cases and a `curl -i` pair from the sandbox: the first `GET` with its `ETag`, `Last-Modified` and `Cache-Control`, and the second with `If-None-Match` answering `304`.

A reviewer checks that the `Cache-Control` visibility is `private`, since articles may become per-user later, that the tag changes when either `title` or `body` changes, that the write routes carry no caching headers, and that existing clients still parse the article JSON. Then they merge; browsers and any proxy in front of the service start revalidating instead of refetching on the next deploy.

## Run it on every Ktor service with uncached reads

A team with several Ktor services starts one run per repository with `POST /o/{org}/sessions`, this prompt and the repository in `resources`. The agent reads each service's own routes and storage, so a service that already stores an updated timestamp gets tags built from it rather than a new column, and each run opens its own pull request.

The key's `webhook_url` receives `run.completed` for each run it starts, with a `session_url` to read the pull request link. Send a `request_id`, a UUID, with each start so a retried call returns the run it already started.

## Why run it on Rush?

Caching headers are easy to add and hard to trust: a tag that does not change on update serves stale data, a `public` visibility leaks a response into a shared cache, and a `304` path that is never tested silently returns a body. In a Rush sandbox the agent starts a real Postgres, runs the service under `testApplication`, sends the conditional requests itself and keeps every response in the transcript, so the pull request shows the `304` and the tag change rather than describing them.

It is also work to hand off from the terminal: start it, let Gradle and the tests run in the cloud, and come back to a pull request with the evidence in the description. The same request runs across every Ktor service the team owns, each in its own sandbox.

## Frequently asked questions

### Why both CachingHeaders and ConditionalHeaders?

`CachingHeaders` sets `Cache-Control` so a client knows how long a response is fresh; `ConditionalHeaders` sets `ETag` and `Last-Modified` and answers `304` when the client sends `If-None-Match` or `If-Modified-Since`. Together they cut both the requests and the bytes; either alone leaves one half undone.

### Does this change the JSON clients receive?

No. The new `updated_at` field on `Article` is optional and omitted when null, so the `title` and `body` shape stays, and the write endpoints answer exactly as before. The tests parse the article body with the same serializer the server uses.

### What about the single JDBC connection the sample uses?

The agent leaves it alone; caching sits above the service layer. Fewer full reads reach the database once clients revalidate, which helps a single connection, but moving to a pool is a separate change and the pull request says so.

### Why is the max-age short and private?

Articles can be edited at any time, so a long freshness window would show stale content; a short one keeps clients revalidating with the tag, which is cheap. `private` keeps shared proxies from storing the response, which matters once any read becomes per-user. Both values are in one place in `Caching.kt` to adjust.

## More Ktor jobs

- [Add Response Compression to a Ktor API](https://getrush.ai/run/add-compression/ktor/)
- [Add Connection Pooling to a Ktor Server with HikariCP](https://getrush.ai/run/add-connection-pooling/ktor/)
- [Add CORS and Rate Limiting to a Ktor Server from a Linear Issue](https://getrush.ai/run/add-cors/ktor/)

## The same job on other stacks

- [Add Caching to a Quarkus App](https://getrush.ai/run/add-caching/quarkus/)
- [Add Caching to a Streamlit App](https://getrush.ai/run/add-caching/streamlit/)
- [Add Caching to a Vapor App](https://getrush.ai/run/add-caching/vapor/)

## 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/)
