Two PRs that add a migration with the same number can both pass CI and merge back to back, leaving main with a duplicate migration. Squash and Merge only reads the recorded status of each PR's head commit, so nothing blocks the second merge. Since March this has needed at least 8 follow-up fixes, two of them yesterday (#32335, #32329). This adds `coderd/database/migrations/LATEST`, a file that names the newest migration. Every migration PR rewrites the same line, so once one merges, GitHub marks the others as conflicting and disables their merge button. The file holds the full migration name rather than just the number, because two PRs that both wrote `000645` would be identical changes, and git merges identical changes cleanly. ## Changes - `scripts/check_migrations_latest.sh` checks that `LATEST` names the newest `*.up.sql` and that no two migrations share a number. It runs in `make lint/migrations`, which `make lint` and `lint-light` already include. With `--write` it rewrites `LATEST`. - `create_migration.sh` writes `LATEST` after creating the migration. - `fix_migration_numbers.sh` rewrites and stages `LATEST` after renumbering. It now reads the branch's migrations from the index instead of `HEAD`, so it works mid-rebase (where `HEAD` doesn't yet contain them) as well as mid-merge. It keeps a migration whose number is already free instead of failing on a same-name `mv`. It also stages its renames when the branch has no fixtures. Before, it returned before `git add` in that case. - Updated `contributing/backend.md` and `.claude/docs` with the conflict workflow. ## Workflow when another migration lands first 1. GitHub shows a conflict in `LATEST`. 2. Merge or rebase onto `main`. While the conflict is still open, run `./coderd/database/migrations/fix_migration_numbers.sh`. It renumbers your migrations only if their numbers are taken, rewrites and stages `LATEST`. 3. Commit, or continue the rebase. Stacked migration PRs also conflict on `LATEST` once the lower PR squash-merges. The same script handles that: it keeps numbers that are still free and only rewrites `LATEST`. ## Compared with #30734 and #30779 Those PRs post a status check that is refreshed when main moves. They still leave a window between a migration landing and the refresh, and they depend on `pull_request_target` and a required-status setup. A git conflict is evaluated at merge time, so this approach has no window and needs no workflow, token or branch protection change. A status check could still sit on top later for a friendlier message. ## Testing In a scratch repo with a local origin: - Two branches that each add `000645_*` and run `--write`: the second merge reports `CONFLICT (content): Merge conflict in coderd/database/migrations/LATEST`. Without `LATEST`, the same two branches merge cleanly into a duplicate `000645`. - After the conflict, rebasing, taking either side and running `fix_migration_numbers.sh` renumbers to `000646`, rewrites `LATEST`, stages everything, and the branch then merges cleanly. Also checked with a matching fixture. - The check fails on duplicates, a stale `LATEST`, or a missing `LATEST`, and passes on current main (`000644_chat_project_templates`). - Running `fix_migration_numbers.sh` while the `LATEST` conflict is still open renumbers and resolves it in both the merge and rebase flows (with a fixture in the rebase case). In a two-PR stack where the lower PR squash-merges, it keeps the upper PR's number and only rewrites `LATEST`. - The check accepts trailing whitespace and CRLF in `LATEST`. - `shellcheck -x` and `shfmt -d` pass on the three scripts, and `make pre-commit-light` passes. ## Notes - Release branches cut before this merges don't have `LATEST`, so cherry-picking a migration PR onto one conflicts on it. Drop the `LATEST` change in that cherry-pick. Release branches cut after this merges do have `LATEST`, so every migration backport conflicts on it, and `cherry-pick.yaml` falls back to its manual-resolution placeholder. Resolve it with `./scripts/check_migrations_latest.sh --write`. The same applies to reverting a migration PR after a later migration has landed. - Rollout: open PRs that add migrations and have green CI from before this merges can still merge without touching `LATEST`, because they don't conflict with it. That would leave `LATEST` stale on `main`, and since PR CI lints the merge ref, `lint/migrations` would fail on every open PR until someone bumps `LATEST`. When this lands, ask the authors of open migration PRs to update from `main`, and be ready to merge a one-line `LATEST` bump. - If a migration lands on main before this merges, `LATEST` needs a bump. `make lint/migrations` will flag it.
16 KiB
Backend
This guide is designed to support both Coder engineers and community contributors in understanding our backend systems and getting started with development.
Coder’s backend powers the core infrastructure behind workspace provisioning, access control, and the overall developer experience. As the backbone of our platform, it plays a critical role in enabling reliable and scalable remote development environments.
The purpose of this guide is to help you:
- Understand how the various backend components fit together.
- Navigate the codebase with confidence and adhere to established best practices.
- Contribute meaningful changes - whether you're fixing bugs, implementing features, or reviewing code.
Need help or have questions? Join the conversation on our Discord server — we’re always happy to support contributors.
Platform Architecture
To understand how the backend fits into the broader system, we recommend reviewing the following resources:
-
General Concepts: Essential concepts and language used to describe how Coder is structured and operated.
-
Architecture: A high-level overview of the infrastructure layout, key services, and how components interact.
These sections provide the necessary context for navigating and contributing to the backend effectively.
Tech Stack
Coder's backend is built using a collection of robust, modern Go libraries and internal packages. Familiarity with these technologies will help you navigate the codebase and contribute effectively.
Core Libraries & Frameworks
- go-chi/chi: lightweight HTTP router for building RESTful APIs in Go
- golang-migrate/migrate: manages database schema migrations across environments
- coder/terraform-config-inspect (forked): used for parsing and analyzing Terraform configurations, forked to include PR #74
- coder/pq (forked): PostgreSQL driver forked to support rotating authentication tokens via
driver.Connector - coder/tailscale (forked): enables secure, peer-to-peer connectivity, forked to apply internal patches pending upstreaming
- coder/wireguard-go (forked): WireGuard networking implementation, forked to fix a data race and adopt the latest gVisor changes
- coder/ssh (forked): customized SSH server based on
gliderlabs/ssh, forked to include Tailscale-specific patches and avoid complex subpath dependencies - coder/bubbletea (forked): terminal UI framework for CLI apps, forked to remove an
init()function that interfered with web terminal output
Coder libraries
- coder/terraform-provider-coder: official Terraform provider for managing Coder resources via infrastructure-as-code
- coder/websocket: minimal WebSocket library for real-time communication
- coder/serpent: CLI framework built on
cobra, used for large, complex CLIs - coder/guts: generates TypeScript types from Go for shared type definitions
- coder/wgtunnel: WireGuard tunnel server for secure backend networking
Repository Structure
The Coder backend is organized into multiple packages and directories, each with a specific purpose. Here's a high-level overview of the most important ones:
- agent: core logic of a workspace agent, supports DevContainers, remote SSH, startup/shutdown script execution. Protobuf definitions for DRPC communication with
coderdare kept in proto. - cli: CLI interface for
codercommand built on coder/serpent. Input controls are defined in cliui, and testdata contains golden files for common CLI calls - cmd: entry points for CLI and services, including
coderd - coderd: the main API server implementation with chi endpoints
- audit: audit log logic, defines target resources, actions and extra fields
- autobuild: core logic of the workspace autobuild executor, periodically evaluates workspaces for next transition actions
- httpmw: HTTP middlewares mainly used to extract parameters from HTTP requests (e.g. current user, template, workspace, OAuth2 account, etc.) and storing them in the request context
- prebuilds: common interfaces for prebuild workspaces, feature implementation is in enterprise/prebuilds
- provisionerdserver: DRPC server for provisionerd instances, used to validate and extract Terraform data and resources, and store them in the database.
- rbac: RBAC engine for
coderd, including authz layer, role definitions and custom roles. Built on top of Open Policy Agent and Rego policies. - telemetry: records a snapshot with various workspace data for telemetry purposes. Once recorded the reporter sends it to the configured telemetry endpoint.
- tracing: extends telemetry with tracing data consistent with OpenTelemetry specification
- workspaceapps: core logic of a secure proxy to expose workspace apps deployed in a workspace
- wsbuilder: wrapper for business logic of creating a workspace build. It encapsulates all database operations required to insert a build record in a transaction.
- database: schema migrations, query logic, in-memory database, etc.
- db2sdk: translation between database structures and codersdk objects used by coderd API.
- dbauthz: AuthZ wrappers for database queries, ideally, every query should verify first if the accessor is eligible to see the query results.
- dbfake: helper functions to quickly prepare the initial database state for testing purposes (e.g. create N healthy workspaces and templates), operates on higher level than dbgen
- dbgen: helper functions to insert raw records to the database store, used for testing purposes
- dbmock: a store wrapper for database queries, useful to verify if the function has been called, used for testing purposes
- dbpurge: simple wrapper for periodic database cleanup operations
- migrations: an ordered list of up/down database migrations, use
./create_migration.sh my_migration_nameto modify the database schema - pubsub: PubSub implementation using PostgreSQL and in-memory drop-in replacement
- queries: contains SQL files with queries,
sqlccompiles them to Go functions - sqlc.yaml: defines mappings between SQL types and custom Go structures
- codersdk: user-facing API entities used by CLI and site to communicate with
coderdendpoints - dogfood: build inputs for the images used by Coder's dogfood workspaces. The workspace templates that consume these images live in an internal Coder infrastructure repository.
- enterprise: enterprise-only features, notice similar file structure to repository root (
audit,cli,cmd,coderd, etc.) - provisioner: supported implementation of provisioners, Terraform and "echo" (for testing purposes)
- provisionerd: core logic of provisioner runner to interact provisionerd server, depending on a job acquired it calls template import, dry run or a workspace build
- pty: terminal emulation for agent shell
- support: compile a support bundle with diagnostics
- tailnet: core logic of Tailnet controller to maintain DERP maps, coordinate connections with agents and peers
- vpn: Coder Desktop (VPN) and tunneling components
Testing
The Coder backend includes a rich suite of unit and end-to-end tests. A variety of helper utilities are used throughout the codebase to make testing easier, more consistent, and closer to real behavior.
clitest
- Spawns an in-memory
serpent.Commandinstance for unit testing - Configures an authorized
codersdkclient - Once a
serpent.Invocationis created, tests can execute commands as if invoked by a real user
ptytest
ptytestattaches to aserpent.Invocationand simulates TTY input/outputptyprovides matchers and "write" operations for interacting with pseudo-terminals
coderdtest
- Provides shortcuts to spin up an in-memory
coderdinstance - Can start an embedded provisioner daemon
- Supports multi-user testing via
CreateFirstUserandCreateAnotherUser - Includes "busy wait" helpers like
AwaitTemplateVersionJobCompleted - oidctest can start a fake OIDC provider
testutil
- General-purpose testing utilities, including:
- chan.go: helpers for sending/receiving objects from channels (
TrySend,RequireReceive, etc.) - duration.go: set timeouts for test execution
- eventually.go: repeatedly poll for a condition using a ticker
- port.go: select a free random port
- prometheus.go: validate Prometheus metrics with expected values
- pty.go: read output from a terminal until a condition is met
- wait_buffer.go: thread-safe
io.Writerthat blocks until accumulated output contains a signal (WaitFor,WaitForNth,WaitForCond)
- chan.go: helpers for sending/receiving objects from channels (
dbtestutil
- Allows choosing between real and in-memory database backends for tests
WillUsePostgresis useful for skipping tests in CI environments that don't run Postgres
quartz
- Provides a mockable clock or ticker interface
- Allows manual time advancement
- Useful for testing time-sensitive or timeout-related logic
Quiz
Try to find answers to these questions before jumping into implementation work — having a solid understanding of how Coder works will save you time and help you contribute effectively.
- When you create a template, what does that do exactly?
- When you create a workspace, what exactly happens?
- How does the agent get the required information to run?
- How are provisioner jobs run?
Recipes
Adding database migrations and fixtures
Database migrations
Database migrations are managed with
migrate.
To add new migrations, use the following command:
./coderd/database/migrations/create_migration.sh my name
/home/coder/src/coder/coderd/database/migrations/000070_my_name.up.sql
/home/coder/src/coder/coderd/database/migrations/000070_my_name.down.sql
Then write queries into the generated .up.sql and .down.sql files and commit
them into the repository. The down script should make a best-effort to retain as
much data as possible.
create_migration.sh also updates
migrations/LATEST to name your new
migration. Commit it with the migration. Every PR that adds a migration changes
that file, so when another migration merges first, GitHub reports your PR as
conflicting instead of letting it merge a duplicate migration number. To fix it,
merge main into your branch, and while the LATEST conflict is still open,
run ./coderd/database/migrations/fix_migration_numbers.sh. The script
renumbers your migrations if their numbers are taken, rewrites LATEST, and
stages the result, so you don't need to edit the conflict by hand. Then commit.
make lint fails if LATEST does not name the newest migration or if two
migrations share a number.
If you rebase instead, don't run fix_migration_numbers.sh at a rebase stop.
On a branch with more than one migration commit, it can leave two migrations
with the same number or swap their order, and make lint does not catch a
swapped order. At each stop, run ./scripts/check_migrations_latest.sh --write
and git add coderd/database/migrations/LATEST, then continue the rebase. When
the rebase finishes, run fix_migration_numbers.sh once and commit the result.
Every pair of open PRs that add migrations conflicts on LATEST, even when
their numbers don't collide. This includes stacked PRs: once the lower PR
squash-merges, the next PR conflicts. Running fix_migration_numbers.sh keeps
numbers that are still free and only rewrites LATEST. If the lower PR was
renumbered onto your migration's number, the script fails and lists both
migrations. Rename yours to the next free number with git mv and run it again.
When a cherry-pick, backport, or revert conflicts on LATEST, resolve it with
./scripts/check_migrations_latest.sh --write, which names the newest migration
on the current branch.
Run make gen to generate models.
Database fixtures (for testing migrations)
There are two types of fixtures that are used to test that migrations don't break existing Coder deployments:
- Partial fixtures
migrations/testdata/fixtures - Full database dumps
migrations/testdata/full_dumps
Both types behave like database migrations (they also
migrate). Their behavior mirrors
Coder migrations such that when migration number 000022 is applied, fixture
000022 is applied afterwards.
Partial fixtures are used to conveniently add data to newly created tables so that we can ensure that this data is migrated without issue.
Full database dumps are for testing the migration of fully-fledged Coder deployments. These are usually done for a specific version of Coder and are often fixed in time. A full database dump may be necessary when testing the migration of multiple features or complex configurations.
To add a new partial fixture, run the following command:
./coderd/database/migrations/create_fixture.sh my fixture
/home/coder/src/coder/coderd/database/migrations/testdata/fixtures/000070_my_fixture.up.sql
Then add some queries to insert data and commit the file to the repo. See
000024_example.up.sql
for an example.
To create a full dump, run a fully fledged Coder deployment and use it to generate data in the database. Then shut down the deployment and take a snapshot of the database.
mkdir -p coderd/database/migrations/testdata/full_dumps/v0.12.2 && cd $_
pg_dump "postgres://coder@localhost:..." -a --inserts >000069_dump_v0.12.2.up.sql
Make sure sensitive data in the dump is desensitized, for instance names, emails, OAuth tokens and other secrets. Then commit the dump to the project.
To find out what the latest migration for a version of Coder is, use the following command:
git ls-files v0.12.2 -- coderd/database/migrations/*.up.sql
This helps in naming the dump (e.g. 000069 above).