Lesson 4 of 9 · 26m
Fluent Models and Migrations That Survive Production
Configure Fluent deliberately, model database truth with explicit migrations, and treat schema evolution as an operational process rather than generated noise.
The dangerous migration is rarely the first one. It is the nineteenth, run during a deploy against millions of rows while old binaries are still serving traffic. Fluent makes schema changes easy to write; it does not make them operationally trivial.
Configure the database explicitly
app.databases.use(.postgres(
hostname: Environment.get("DATABASE_HOST") ?? "127.0.0.1",
port: Environment.get("DATABASE_PORT").flatMap(Int.init) ?? 5432,
username: Environment.get("DATABASE_USER") ?? "vapor",
password: Environment.get("DATABASE_PASSWORD") ?? "dev-only-password",
database: Environment.get("DATABASE_NAME") ?? "vapor_dev",
tls: .prefer(try .init(configuration: .clientDefault))
), as: .psql)Convenient defaults are for development. Production should fail fast when required configuration is absent rather than quietly connect to the wrong database.
Models are persistence truth
final class Project: Model, @unchecked Sendable {
static let schema = "projects"
@ID(key: .id) var id: UUID?
@Field(key: "tenant_id") var tenantID: UUID
@Field(key: "name") var name: String
@Timestamp(key: "created_at", on: .create) var createdAt: Date?
@Timestamp(key: "deleted_at", on: .delete) var deletedAt: Date?
init() {}
}Treat models as short-lived persistence objects. They are not automatically safe shared state because they use reference-type framework machinery.
Migrations are deliberate schema design
struct CreateProjects: AsyncMigration {
func prepare(on database: Database) async throws {
try await database.schema(Project.schema)
.id()
.field("tenant_id", .uuid, .required)
.field("name", .string, .required)
.field("created_at", .datetime)
.field("deleted_at", .datetime)
.unique(on: "tenant_id", "name")
.create()
}
func revert(on database: Database) async throws {
try await database.schema(Project.schema).delete()
}
}Indexes, uniqueness, nullability, and deletion behavior are decisions. A missing index on tenant_id is invisible in development and painful at production scale.
Destructive changes need phases
add compatible column -> deploy dual readers/writers
-> backfill in batches -> deploy new reads -> remove old shape laterNo ORM can automate away version overlap. Run migrations from one controlled release job, not simultaneously from every replica at boot.
Field notes
- Unique constraints belong in the database because application validation races.
- Large backfills need batching, observation, and an abort plan.
- Cascading deletes can destroy auditability; consider soft deletion or explicit cleanup.
- If rollback is impossible, document the restore path instead of pretending otherwise.
Was this lesson helpful?