Blog
Spec-Driven Data Engineering: Why You Should Stop Writing SQL First
Data engineering has a specification problem. We solve it the same way software engineering did — by putting the spec before the code.

The merchandising team asks for “product profitability by category.” Simple enough, right?
Before you write a single line of SQL, count the decisions you need to make: Which source tables — inventory, orders, or both? What counts as “revenue” — the listed retail price or the actual sale price the customer paid? What about returned orders — do they count as revenue, as a cost, or get excluded entirely? Cancelled orders? How do you handle unsold inventory sitting in a warehouse — it has a cost but no revenue, so does it belong in a profitability model? What about products sold below cost? The existing inventory model already tracks sell-through rate using retail price — do you extend it or build something new? Which downstream dashboards break if you change the grain? What tests should you write? Who owns the margin definition?
That's more than a dozen decisions, and you haven't written a single line of SQL yet. This is the specification problem: in traditional data engineering, these decisions live in Slack threads, Confluence pages nobody reads, and the engineer’s head. The specification is implicit. The SQL code is the only artifact. And when the code is the spec, every change carries more uncertainty than it should.
Software engineering solved this decades ago. API-first development (OpenAPI), Test-Driven Development, Design by Contract — these paradigms all share a common insight: the specification should precede the implementation. Data engineering is finally catching up, and AI is the catalyst that makes it practical.
In this post, I’ll walk through an approach that treats structured specifications as the primary artifact in data engineering — not static documents that gather dust, but living contracts that drive implementation, testing, governance, and even code generation. The core idea: the engineer’s job shifts from writing code that embodies decisions to making decisions that constrain code. AI gathers context, proposes spec sections, and generates implementation — the engineer validates and approves. I’ll show what a data engineering spec looks like in practice, how this workflow plays out, and where it falls short.
What Is Spec-Driven Development?
Spec-Driven Development (SDD) is a paradigm where a structured specification is the primary artifact. Code is a derived output — generated, validated, and constrained by the spec.
The concept isn’t new — it draws on Test-Driven Development and Design by Contract — but it experienced a renaissance in 2025 when LLM-powered agentic coding made spec-to-code generation practical. ThoughtWorks placed SDD in their Technology Radar’s “Assess” ring — worth exploring.
InfoQ frames SDD as a layered architecture — from declarative specs through code generation to runtime validation — where architecture becomes enforceable rather than advisory.
Here’s the thing: data engineering has been building toward this without naming it. Data contracts, dbt model contracts, schema-driven development — these are all proto-SDD. They formalize agreements about data structure, semantics, and quality. A full specification simply extends this idea across the entire lifecycle of a data transformation: from business intent to governance sign-off.
Why Data Engineering Is Ready for This
We already revolve around metadata
Look at any mature dbt project. YAML schema files define column types and descriptions. Tests enforce constraints. Semantic models declare metrics and dimensions. Freshness checks define SLAs. These are specifications — we just scatter them across a dozen files and don’t treat them as the primary artifact.
The metadata is already there. The question is whether we organize it into a coherent contract or leave it fragmented.
The abstraction ladder keeps climbing
Data engineering has been steadily raising its level of abstraction:

Each step captures more intent with less boilerplate. Declarative pipelines already show significant code reduction compared to imperative approaches. Specs push this further by capturing the why alongside the what — business context, edge case decisions, quality thresholds, and governance approvals that imperative code can never express.
AI agents need structured context
This is the point that makes SDD practical now, not just theoretically appealing. AI agents are evolving from code generators to specification interpreters — and they need structured input to do it well. Xebia's guide on structuring a dbt project for AI-powered development shows what that structured input looks like in practice.
A YAML data contract is a far better prompt than “build me a pipeline.” The more structured your specification, the more reliably an AI agent can generate correct implementations. Without specs, AI-assisted data engineering is just prompt-and-pray. Fast, but fragile.
The benchmarks make this concrete. These are raw text-to-SQL tasks: schema plus question, no semantic layer, no business context. On the enterprise-realistic Spider 2.0 benchmark, GPT-4o scores around 10% execution accuracy when faced with real-world schemas of 3,000+ columns across Snowflake and BigQuery. The BIRD benchmark tells a similar story. Top single-model systems plateau around 76%, while humans score 93% on the same tasks. The gap lives in exactly the places a spec would help: ambiguous column names, multi-step joins, domain-specific filters, aggregation edge cases. Structured context consistently outperforms raw prompting.
AI also solves the historical objection to specs: who has time to write all that? When an AI agent can auto-populate spec sections by querying your schema, semantic layer, lineage graph, and data quality tools — and the engineer only fills in what the machine can’t infer — the upfront cost drops dramatically.
Governance demands traceability
Regulatory requirements (GDPR, SOX, DORA for EU financial services) increasingly demand auditability of data transformations. A spec creates an auditable decision trail: who requested what, which metrics are defined how, what edge cases were considered, who approved. This isn’t optional for teams operating in regulated industries — and a spec-driven workflow provides it as a byproduct rather than a bolted-on compliance exercise.
Anatomy of a Data Engineering Spec
Let’s make this concrete. The merchandising team wants product profitability by category — gross margin, sell-through rate, and the cost of unsold inventory. An inventory model already exists, but it uses retail price instead of actual sale price for revenue. Here’s what a full specification looks like, section by section:
1. Business Context — Why this exists
Intent: Provide product profitability metrics per category and department,
reconciling inventory costs with actual transaction revenue to support
merchandising decisions (pricing, assortment, markdowns).
Report consumer: Merchandising team — category margin analysis, markdown
decisions. Secondary: Finance team for COGS reconciliation.
Definition of success: Each row = one product category + one department.
Margin calculated from actual sale_price (not retail_price). Unsold
inventory carrying cost tracked separately. No NULL categories or
departments.
This section forces a conversation that often doesn’t happen raw. What does “revenue” mean here? The existing fct_inventory_status model uses retail price — the listed catalog price. But this spec explicitly demands actual sale price — what the customer paid, which can be lower due to discounts. That’s a completely different number, and the distinction only surfaces when you write it down.
2. Semantic Layer — What we’re measuring
Metrics:
gross_revenue — SUM(sale_price) for completed orders
cost_of_goods_sold — SUM(inventory cost) for sold items
gross_margin — gross_revenue - cost_of_goods_sold
gross_margin_pct — gross_margin / gross_revenue * 100 (derived)
units_sold — COUNT of inventory items with a sale
units_unsold — COUNT of inventory items without a sale
sell_through_rate — units_sold / (units_sold + units_unsold) * 100 (derived)
unsold_carrying_cost — SUM(cost) for unsold inventory items
Dimensions:
category — product category (Swim, Jeans, Dresses, etc.)
department — Men, Women
Grain: one row = one category + one department
Notice eight metrics, three of them derived. When connected to a semantic layer, an AI agent can auto-populate this section — pulling existing metric definitions and flagging conflicts. Here, it would discover that the existing fct_inventory_status model already defines sell_through_rate and revenue_from_sold but calculates them differently (using retail price, not sale price). That conflict is exactly the kind of thing a spec surfaces before it becomes an engineer’s headache or a production bug.
3. Data Sources & Lineage — Where data comes from
Source tables:
inventory_items — inventory stock: cost, sold_at, product_id
order_items — order lines: sale_price, product_id, order_id, status
orders — order header: status, user_id, created_at
products — product catalog: category, department, retail_price, cost
Intermediate transformations:
stg_inventory_items — casts cost to DECIMAL(10,2), timestamps
stg_order_items — sale_price cast to DECIMAL(10,2)
stg_orders — casts timestamps
stg_products — casts cost, retail_price to DECIMAL(10,2)
int_order_items_enriched — joins items + orders + users, adds order_status
Upstream dependency chain:
Two parallel paths converge:
Path A (cost): inventory_items → stg_inventory_items → join products
Path B (revenue): order_items → int_order_items_enriched (via
stg_order_items + stg_orders) → filtered to 'Complete'
Reconciled via: inventory_item_id (links an inventory unit to its sale)
This is where the spec gets interesting. The lineage reveals that profitability requires reconciling two independent data paths — the inventory/cost path and the transaction/revenue path — linked by inventory_item_id. With lineage tooling, an AI agent traces both paths automatically. Without it, the engineer documents this manually — which is itself valuable, because it forces you to understand the join strategy before writing code.
4. Technical Specification — How it’s built
Output: fct_product_profitability (materialized as table)
Aggregation logic:
Inventory base: stg_inventory_items joined to stg_products on product_id
Revenue overlay: LEFT JOIN to int_order_items_enriched on
inventory_item_id, filtered to order_status = 'Complete'
GROUP BY category, department
Edge cases:
- sale_price vs retail_price vs cost: margin uses sale_price - cost,
NOT retail_price - cost. Existing model intentionally diverges.
- Returned orders (order_status = 'Returned'): EXCLUDE from revenue.
- Cancelled orders (order_status = 'Cancelled'): Exclude entirely.
- Items sold below cost (negative margin): INCLUDE.
- Unsold inventory: tracked as unsold_carrying_cost, not in margin.
- inventory_items.cost vs products.cost: use inventory_items.cost.
- Multiple inventory batches: aggregation at item level handles this.
The edge cases section is where specs earn their keep. Consider the returned orders decision: an inventory item marked as “sold” actually had its revenue reversed. SQL won’t tell you this — a WHERE sold_at IS NOT NULL looks correct but includes returns. The spec forces you to think about the semantic gap between “sold in the warehouse” and “revenue recognized.”
5. Impact Analysis — What it affects
Downstream models:
fct_inventory_status — High risk: overlapping metrics,
different revenue definition.
rpt_executive_dashboard — Medium risk: may add profitability KPIs.
Existing conflicts:
fct_inventory_status.sell_through_rate uses COUNT(sold_at) / COUNT(*).
fct_product_profitability.sell_through_rate excludes returned items.
Decision: document divergence, propose deprecating
fct_inventory_status.revenue_from_sold in a follow-up.
Risk assessment: High. Conflicting profitability metrics across two
models will confuse consumers.
This is a brownfield model — it partially overlaps with an existing one. The impact analysis surfaces a real problem: two models will report different sell-through rates for the same product category. Without a spec, this conflict would only surface when a stakeholder notices mismatched numbers in two dashboards.
6. Quality Assurance — How we know it’s correct
dbt tests:
not_null — category, department, gross_revenue
unique_combination_of_columns — [category, department]
expression_is_true — units_sold + units_unsold > 0
expression_is_true — gross_margin_pct BETWEEN -100 AND 100
expression_is_true — unsold_carrying_cost >= 0
relationships — category references dim_products.category
Data quality thresholds:
NULL rate on category — 0% → block deploy
gross_margin_pct outliers — < -50% → warn
sell_through_rate vs previous — ±15% → warn
gross_revenue vs fct_inventory_status — divergence expected,
document ratio per category for reconciliation audit
Tests defined before the code exists. The most interesting test: comparing gross_revenue against the existing fct_inventory_status.revenue_from_sold. We expect them to differ (sale price vs. retail price), but tracking the ratio per category provides a reconciliation audit trail.
7. Governance Checklist — Is it ready to ship?
- [ ] Metric owner identified (Merchandising team — primary consumer,
Finance team — COGS reconciliation)
- [ ] Lineage complete from source to output
(inventory_items → stg_inventory_items → join stg_products;
order_items → int_order_items_enriched → filtered to 'Complete';
reconciled via inventory_item_id → fct_product_profitability)
- [ ] Tests cover grain and key columns
(uniqueness on category + department, not_null on all measures,
margin sanity bounds, cross-model reconciliation)
- [ ] Downstream conflicts documented
(fct_inventory_status uses retail_price — divergence acknowledged,
deprecation of revenue_from_sold proposed)
- [ ] Edge cases addressed in Technical Specification
(returned orders excluded, cancelled orders excluded, items below
cost included, unsold inventory tracked separately, correct cost
source identified, price column disambiguation)
A five-point validation gate. The governance checklist for a brownfield model is more demanding: it requires documenting downstream conflicts, not just confirming “no broken dependencies.” An AI agent can verify most items automatically, but the metric owner sign-off and the decision to deprecate the conflicting metric remain human decisions.
The spec lifecycle: The spec is a living document with a status, not a one-time design doc that rots in Confluence.

The Spec-Driven Workflow in Practice
Step 1: Capture project standards (once)
Before generating any specs, you capture your project’s conventions: what platform you’re on, what naming patterns you use, which modeling methodology (Kimball, Data Vault, etc.), what SQL style you prefer, which tools are available for schema discovery and lineage. These standards become reusable context.
Step 2: Scaffold the spec
An engineer describes a feature: “product profitability by category for merchandising.” An AI agent parses this, detects that a related model (fct_inventory_status) already exists, classifies this as a brownfield change, and queries available tools to auto-populate every spec section it can. The agent classifies what it has discovered as Populated (fully covered), Partial (gaps remain), or Empty (needs engineer input).
Step 3: Ask only what’s missing
Instead of bombarding the engineer with 20 questions, the workflow classifies questions as blocking (must answer: output grain, metric definition, filter logic) versus non-blocking (nice to have: dbt tags, QA thresholds). Blocking questions come first; non-blocking questions are batched and dropped if unanswered.
Step 4: Generate, enrich, validate
The spec is generated with all sections filled. Auto-populated sections are marked transparently. Then enrichment: impact analysis traces downstream consumers, test suggestions propose dbt tests, and a governance checkpoint validates the five-point checklist.
Step 5: Implement from the approved spec
Only after the spec is approved does implementation begin. The spec constrains the implementation — column names, aggregation logic, edge case handling, test expectations are all defined. Code becomes a derivation, not an invention.
Spec-Driven vs. Traditional Data Engineering: How They Differ
| Aspect | Traditional | Spec-Driven |
|---|---|---|
| Primary artifact | SQL code | Structured specification |
| Business context | Scattered across Slack/tickets | Captured in section 1 |
| Schema decisions | Implicit in code | Explicit in section 4 |
| Impact assessment | grep + tribal knowledge | Systematic, pre-implementation |
| Test strategy | Added after implementation | Defined before code exists |
| Governance | End-of-sprint checkbox | Integrated validation gate |
| Knowledge transfer | Ask Sarah, she built it | Self-documenting specs |
| AI assistance | "Write me a dbt model" | "Implement this spec" |
| Onboarding | Read SQL, infer intent | Read spec, understand intent |
The fundamental shift: spec captures intent; code captures implementation. You can review the what and why without reading SQL. A business stakeholder can validate sections 1–2 of a spec. A data engineer implements sections 3–7. The spec acts as a contract between them.

Not every layer needs the same level of specification. Staging models that rename and cast columns need little more than a schema definition and a freshness SLA. Intermediate models that join and enrich data deserve lineage documentation and test definitions. Marts and serving layers — where mistakes propagate to dashboards, reports, and downstream systems — warrant the full seven sections. Birgitta Böckeler’s analysis of SDD tools (on martinfowler.com) raises valid concerns: specs can become unwieldy, AI agents don’t always follow them faithfully, and the approach struggles when scope isn’t well-understood upfront. The gradient is the answer — spec the layers where the cost of getting it wrong is high, skip the layers where exploration matters more than precision.
This extends to tooling maturity too: nothing in this workflow requires specific tooling. No metadata catalog? Fill in source tables manually. No semantic layer? Define metrics in plain text. Teams with rich tooling get more automation; teams with minimal tooling get a structured template that guides them to the right questions. The spec is valuable either way.
An Honest Assessment
Where Specs Shine
Reduced ambiguity. Decisions are made upfront in a reviewable format, not discovered mid-implementation or during a frantic PR review.
AI-ready by design. Structured specs give AI agents exactly what they need: constrained, unambiguous context. “Implement this spec” is a fundamentally better prompt than “write me a dbt model for product profitability.”
Governance as a byproduct. Auditability, traceability, and approval workflows are part of the process, not bolted on after the fact.
Knowledge preservation. Specs survive team turnover. A new engineer reads the spec and understands intent, edge cases, and quality expectations — without git blame archaeology.
Faster stakeholder feedback. A business analyst can review a spec. They cannot review a PR full of SQL window functions.
Reusable standards. Project conventions are captured once and applied to every spec automatically.
Where Specs Struggle
Upfront investment. Writing specs takes time. For simple, well-understood transformations, a full spec is overhead. The specification gradient helps, but teams need to develop judgment about when a spec is warranted.
Spec maintenance. Specs must stay in sync with implementation. A stale spec is worse than no spec — it’s actively misleading. Treating specs as version-controlled artifacts alongside the code helps.
Exploration friction. For genuinely exploratory work — profiling a new data source, prototyping a metric definition, ad-hoc analysis — specs add friction. The pragmatic answer: don’t spec exploratory work. Spec the thing you build after you’ve explored.
Cultural change. Teams accustomed to “just write the SQL” need to adopt new habits. Start with one domain, prove the value, expand.
The over-specification risk. ThoughtWorks flagged the “bitter lesson” concern: handcrafting detailed rules for AI may not scale as models improve. This is a real tension — but specs serve humans too (governance, knowledge transfer, stakeholder alignment), so their value isn’t purely about constraining AI.
The Role of AI: Not Replacement, Redistribution
AI doesn’t replace the data engineer — it shifts where they spend their time. Today, most of that time goes to writing SQL, tracing lineage by hand, and explaining models to colleagues. In a spec-driven workflow, the engineer focuses on decisions: defining metrics, resolving edge cases, validating what AI proposes. AI handles the mechanical work — discovering schemas, drafting spec sections, generating transformation code.

The spec becomes the interface between human judgment and machine execution. Engineers encode business knowledge, edge cases, and quality expectations. AI handles the mechanical translation. Each does what they’re best at.
Why does this matter now? Because most developers now report using AI coding tools regularly (85% according to the 2025 JetBrains State of Developer Ecosystem). But without structured specifications, AI-assisted data engineering risks optimizing for speed over correctness. Specs turn AI from a code generator into a specification interpreter.
What's Next for Spec-Driven Data Engineering
The pieces are converging. Data contracts are becoming an industry standard, with tooling for enforcement maturing rapidly. The declarative data stack is consolidating — dbt, SQLMesh, Dagster, Snowflake Dynamic Tables, Databricks Delta Live Tables — all pushing toward “define what you want, not how to get it.” And AI agents are getting better at reading structured context, tracing lineage, and generating constrained implementations.
Spec-driven development sits at the intersection of these three trends. It’s not a new tool to adopt — it’s a way of organizing the metadata, contracts, and conventions you already have into a coherent workflow.
Here’s my challenge: pick your most complex mart model. The one with the most business logic, the most edge cases, the most downstream consumers. Write down, in plain text, the business context, the grain, the source tables, the edge case decisions, and the tests. Chances are you’ll surface at least a few decisions that currently live only in someone’s head — or worse, in no one’s head at all, just implicitly encoded in a SQL WHERE clause that no one remembers writing.
That exercise — surfacing implicit knowledge into an explicit, reviewable, version-controlled format — is the core of spec-driven data engineering. It’s valuable with or without AI. The discipline of structured thinking about your data transformations catches ambiguity, preserves knowledge, and makes governance tractable — none of that requires a language model. What AI changes is the economics: it lowers the cost of writing specs dramatically, making a practice that was always worthwhile finally practical at scale. The best data engineers have always been specification thinkers. AI is starting to remove the excuse not to be.
Watch the on-demand webinar GenAI for Data Teams: AI-Assisted Engineering in Data Lakehouse to see how MCP, spec-driven development, and conversational data interfaces come together in a real Data Lakehouse architecture.
Sources
Spec Driven Development: When Architecture Becomes Executable — InfoQ
Spec-driven development — ThoughtWorks Technology Radar
Understanding Spec-Driven-Development — Birgitta Böckeler (martinfowler.com)
The product profitability example in this article is based on TheLook eCommerce, a synthetic e-commerce dataset originally published by Google as a BigQuery public dataset.
Graphics for this content were generated by Google’s Gemini
Frequently Asked Questions
Written by
Our Ideas
Explore More Blogs
Contact














