Catalogue / data-layer-engineering
data-layer-engineering
Older skill: source not recordedSignedGuides the agent through designing relational and document database schemas, writing advanced SQL and aggregation queries, adding indexes, diagnosing slow queries, building Redis caching layers, and applying schema migrations safely. Trigger when the user asks about PostgreSQL, MySQL, MongoDB, Redis…--- name: data-layer-engineering description: Guides the agent through designing relational and document database schemas, writing advanced SQL and aggregation queries, adding indexes, diagnosing slow queries, building Redis caching layers, and applying schema migrations safely. Trigger when the user asks about PostgreSQL, MySQL, MongoDB, Redis, Prisma, schema design, query tuning, indexes, or data modeling. Do not trigger for frontend styling, static site content, or in-memory-only state. ---
Data Layer Engineering
Use this skill whenever you need to design, query, optimize, or evolve a persistence layer. Work through the sections in order: pick the right store, design the schema, write the queries, tune them, add caching, and plan migrations.
Step 1: Match the Storage to the Access Patterns
Before writing any schema, ask the user (or infer from the code) how the data is read and written:
- Relational (PostgreSQL, MySQL): choose when records relate to each other, you need joins, multi-row atomic writes, or strong constraints.
- Document (MongoDB): choose when documents are read as whole nested objects, fields vary between records, and horizontal write scale matters.
- Cache (Redis): choose as a companion layer for hot reads, sessions, counters, queues, and rate limits — never as the sole source of truth.
Combining all three is normal: relational for truth, document store for read-shaped payloads, cache in front of the hot path.
Step 2: Design Relational Schemas
Apply these rules to every table:
- Generate primary keys server-side (UUIDs or identity columns) so clients never invent IDs.
- Mark every required column
NOT NULL; give defaults where sensible. - Constrain enum-like values with
CHECKconstraints instead of trusting application code. - Declare foreign keys explicitly and choose delete behavior deliberately: cascade for owned child rows, restrict for rows history depends on.
- Add
created_at/updated_attimestamps with time zones. - Model many-to-many relationships with a junction table keyed on both sides.
Example — an orders domain:
CREATE TABLE customers (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email TEXT NOT NULL UNIQUE,
full_name TEXT NOT NULL,
tier TEXT NOT NULL DEFAULT 'standard'
CONSTRAINT valid_tier CHECK (tier IN ('standard', 'premium', 'enterprise')),
settings JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE RESTRICT,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled')),
total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
placed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE order_items (
order_id UUID NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
product_sku TEXT NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price_cents INTEGER NOT NULL,
PRIMARY KEY (order_id, product_sku)
);Add indexes after you know the queries, not before. The three highest-value patterns:
-- Every foreign key used in joins and filters
CREATE INDEX idx_orders_customer ON orders(customer_id);
-- Partial index when queries always filter one status
CREATE INDEX idx_orders_open ON orders(placed_at DESC)
WHERE status IN ('pending', 'paid');
-- Expression index for case-insensitive lookups
CREATE INDEX idx_customers_email_ci ON customers(LOWER(email));Step 3: Write Queries with the Right Tool
- Use a CTE to break a multi-step analysis into named stages.
- Use window functions when you need per-group rankings or running totals without collapsing rows.
- Use a recursive CTE for tree-structured data (categories, org charts).
- Use JSONB operators for semi-structured attributes, not for data you filter on constantly.
Revenue per customer, top 10:
WITH spend AS (
SELECT customer_id, SUM(total_cents) AS spent, COUNT(*) AS order_count
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
)
SELECT c.full_name, s.order_count, s.spent
FROM spend s
JOIN customers c ON c.id = s.customer_id
ORDER BY s.spent DESC
LIMIT 10;Rank each customer's orders by recency:
SELECT
c.full_name,
o.id AS order_id,
o.placed_at,
ROW_NUMBER() OVER (PARTITION BY o.customer_id ORDER BY o.placed_at DESC) AS recency_rank,
o.placed_at - LAG(o.placed_at) OVER (
PARTITION BY o.customer_id ORDER BY o.placed_at
) AS gap_since_previous
FROM orders o
JOIN customers c ON c.id = o.customer_id;Walk a category tree:
WITH RECURSIVE tree AS (
SELECT id, name, parent_id, 1 AS depth, ARRAY[name] AS path
FROM categories WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.name, c.parent_id, t.depth + 1, t.path || c.name
FROM categories c JOIN tree t ON c.parent_id = t.id
)
SELECT * FROM tree ORDER BY path;Read and update JSONB:
SELECT settings->>'theme' AS theme
FROM customers
WHERE settings @> '{"marketing_opt_in": true}';
UPDATE customers
SET settings = jsonb_set(settings, '{last_login}', to_jsonb(now()))
WHERE id = $1;Step 4: Diagnose and Fix Slow Queries
When a query is slow, never guess — inspect its execution plan with analysis and buffer details enabled, then look for:
- Sequential scans over large tables → add an index on the filtered/joined columns.
- Heap fetches dominating → consider a covering index that includes the selected columns so the table is never touched.
- Huge append-only time-series tables → a BRIN index on the timestamp column is small and fast; consider range partitioning by month or quarter.
- Index bloat on write-heavy tables → fewer, broader indexes rather than one per query shape.
EXPLAIN (ANALYZE, BUFFERS) SELECT o.id, c.full_name FROM orders o JOIN customers c ON c.id = o.customer_id WHERE o.status = 'paid' ORDER BY o.placed_at DESC LIMIT 20;
Re-run the plan after each change and report the before/after numbers to the user.
Step 5: Model Documents in MongoDB
Decide field by field, not collection by collection:
- Embed subdocuments that are always read with the parent and bounded in size (an order's line items).
- Reference collections that grow without limit or are queried independently (a customer's orders).
- Denormalize read-time values (product names copied into order items, running counters) and accept a write-time update cost.
// Embedded line items, referenced customer, denormalized totals
{
_id: ObjectId("..."),
customerId: ObjectId("..."),
status: "paid",
items: [
{ sku: "KB-01", name: "Mechanical Keyboard", qty: 1, unitPriceCents: 8900 }
],
totals: { itemsCents: 8900, taxCents: 623, grandTotalCents: 9523 },
placedAt: ISODate("2024-05-02T10:14:00Z")
}
db.orders.createIndex({ customerId: 1, placedAt: -1 });
db.orders.createIndex({ status: 1, placedAt: -1 });Structure aggregation pipelines so the cheap, selective stages run first: match → lookup/unwind → group → sort → limit → project.
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $unwind: "$items" },
{
$group: {
_id: "$items.sku",
unitsSold: { $sum: "$items.qty" },
revenueCents: { $sum: { $multiply: ["$items.qty", "$items.unitPriceCents"] } }
}
},
{ $sort: { unitsSold: -1 } },
{ $limit: 10 },
{ $project: { _id: 0, sku: "$_id", unitsSold: 1, revenueCents: 1 } }
]);Step 6: Add a Redis Caching Layer
Pick the structure that matches the job: strings for single cached values with TTLs, hashes for object fields, sorted sets for rankings and sliding windows, lists or streams for job queues, HyperLogLog for approximate unique counts.
Follow the cache-aside discipline:
- Check the cache key first; return immediately on a hit.
- On a miss, load from the database, then write the value to the cache with a TTL.
- After any successful write to the database, delete the affected cache key — never try to "update" a cached value in place.
async function getCustomer(id: string) {
const key = `customer:${id}`;
const hit = await redis.get(key);
if (hit) return JSON.parse(hit);
const customer = await db.customer.findUnique({ where: { id } });
if (customer) await redis.setex(key, 3600, JSON.stringify(customer));
return customer;
}
async function updateCustomer(id: string, data: UpdateInput) {
const customer = await db.customer.update({ where: { id }, data });
await redis.del(`customer:${id}`);
return customer;
}Fixed-window rate limiting:
async function allowRequest(clientId: string, limit: number, windowSeconds: number) {
const key = `rl:${clientId}`;
const count = await redis.incr(key);
if (count === 1) await redis.expire(key, windowSeconds);
return count <= limit;
}Step 7: Use the ORM as the Primary Interface
Prefer an ORM (Prisma shown here) for type safety and composable filters; drop to raw SQL only for features the ORM cannot express. Define relations, delete behaviors, and indexes in the schema file:
model Customer {
id String @id @default(cuid())
email String @unique
orders Order[]
createdAt DateTime @default(now())
}
model Order {
id String @id @default(cuid())
status OrderStatus @default(PENDING)
totalCents Int
customer Customer @relation(fields: [customerId], references: [id])
customerId String
placedAt DateTime @default(now())
@@index([customerId, placedAt(sort: Desc)])
@@index([status])
}Always select only the columns you need, use interactive transactions when later steps depend on earlier results, and pass values into raw queries as parameters:
const orders = await prisma.order.findMany({
where: { status: 'PAID', customer: { email: { endsWith: '@acme.test' } } },
select: { id: true, totalCents: true, placedAt: true },
orderBy: { placedAt: 'desc' },
take: 20,
});
await prisma.$transaction(async (tx) => {
const item = await tx.product.findUniqueOrThrow({ where: { sku } });
if (item.stock < qty) throw new Error('Insufficient stock');
await tx.product.update({ where: { sku }, data: { stock: { decrement: qty } } });
await tx.order.create({ data: { customerId, totalCents: item.priceCents * qty } });
});Step 8: Evolve the Schema with Versioned Migrations
Never edit a schema in place on a live database. Follow the additive sequence so every step is reversible and non-blocking:
- Generate a named, versioned migration file from the schema change.
- Add new columns as nullable first; backfill existing rows in batches.
- Only after the backfill completes, add
NOT NULL, uniqueness, or check constraints. - Apply migrations to a local or throwaway copy and verify before touching anything shared.
-- Inside a versioned migration: add, backfill, then tighten
ALTER TABLE orders ADD COLUMN currency TEXT;
UPDATE orders SET currency = 'usd' WHERE currency IS NULL;
ALTER TABLE orders ALTER COLUMN currency SET NOT NULL;
ALTER TABLE orders ADD CONSTRAINT valid_currency CHECK (currency IN ('usd', 'eur'));Regenerate the ORM client after any schema change so types stay in sync.
Guardrails
- Never build SQL or query filters by concatenating or interpolating user-supplied input into query text — always use parameterized queries or the ORM's filter objects.
- Never run a migration, schema change, or bulk data rewrite against a staging, shared, or production database without first stating exactly what will change and getting explicit confirmation from the user. Confirm that a backup or rollback path exists before proceeding.
Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 13.1 kB | 387cafdca662 |
| examples.json | 1.3 kB | 7bcfcf829f06 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 0.1.1 Current | Not recorded | 2 Oct 2026 | |
| 0.1.0 | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.