Backend Foundation — Skills & Patterns
Next module →
Backend Foundation — 03

Skills & Patterns
Repeating Patterns, Written Once.

A skill file codifies a repeating code pattern — exception classes, test structure, module scaffold — so the AI applies it consistently across every sprint without re-prompting.

Read time20 min
LevelIntermediate
Quiz3 questions
TrackBackend Foundation
01 — the problem

Without skill files, the AI drifts back to its defaults every session.

You correct the pattern, it holds for one session, then resets on the next. Skill files break that cycle permanently.

Without a skill file, the AI guesses your pattern from context. Sometimes right, often not — wrong exception class, different test structure, error messages that don't match the codebase. The real cost is the correction loop: you correct it, it drifts on the next task. You re-explain the pattern, it holds one session, resets the next.

Skill files break that cycle. The pattern is written down once. It applies every session, every task, for every developer on the team — because the AI reads the file, not your memory.

Skill files live in skills/ inside the project repo — git-tracked, shared with the team, and active for anyone who clones the repo. CLAUDE.md is the bridge: it tells the AI when to read each skill file.

02 — error-handling skill

skills/error-handling.SKILL.md — the NestJS exception map.

TiffinConnect's error-handling skill contains 10 scenarios, a throw pattern, a message format table, and an explicit anti-patterns section. The AI reads it before throwing any error in a service.

ScenarioException classHTTP
Order / user / vendor not foundNotFoundException404
Invalid state transitionUnprocessableEntityException422
Vendor capacity exceededConflictException409
Cutoff time has passedBadRequestException400
Wrong role / forbidden resourceForbiddenException403
Duplicate webhook eventDo not throw — return 200200
DTO field validation failureDo not throw — ValidationPipe handles it400
typescript
// Throw pattern enforced by the skill
throw new NotFoundException(`Order ${id} not found`);
throw new ConflictException(`Vendor ${vendorId} has no available capacity`);
throw new ForbiddenException(`Only vendors may approve orders`);

// Anti-patterns the skill explicitly blocks:
// ❌ manual response — HttpExceptionFilter won't run
res.status(404).json({ message: 'not found' });

// ❌ raw Error — produces a 500, not a 404
throw new Error('order not found');

// ❌ swallowing in controller — hides real errors
try { ... } catch (e) { return { success: false, message: e.message }; }
03 — unit-test skill

skills/unit-test.SKILL.md — Jest mock patterns for Mongoose.

The unit-test skill contains the standard test skeleton, three Mongoose mock patterns, and a 6-item coverage checklist. The AI reads it before writing any spec file.

typescript
// Standard skeleton — enforced by the skill
describe('RatingsService', () => {
  let service: RatingsService;
  let mockModel: any;

  beforeEach(async () => {
    mockModel = jest.fn();
    mockModel.findById = jest.fn();
    mockModel.find = jest.fn();

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        RatingsService,
        { provide: getModelToken(Rating.name), useValue: mockModel },
      ],
    }).compile();

    service = module.get<RatingsService>(RatingsService);
  });

  afterEach(() => jest.clearAllMocks());
});

// Pattern A — query chain (find, findById, findOne)
mockModel.findById.mockReturnValue({
  exec: jest.fn().mockResolvedValue(mockRating)
});

// Pattern B — constructor + save
const mockSave = jest.fn().mockResolvedValue(mockRating);
mockModel.mockImplementation(() => ({ save: mockSave }));

// Pattern C — findByIdAndUpdate
mockModel.findByIdAndUpdate.mockReturnValue({
  exec: jest.fn().mockResolvedValue(updated)
});

The three mock patterns cover 95% of Mongoose operations. Without this skill, the AI invents a fourth pattern that doesn't work with the query chain — the most common source of failing tests in NestJS projects.

04 — debug skill

skills/debug.SKILL.md — the reproduce → isolate → fix loop, written down.

Bug fixing repeats the same steps every time, so it is a perfect candidate for a skill. A project-specific debug skill teaches the AI your repro commands, log locations, and stack — so "run the debug skill on this failure" replaces re-explaining the loop each session.

PhaseWhat the skill makes the AI do
ReproduceRun the project's repro command; capture expected vs actual. Refuse to patch without a reproduction.
IsolateRead the relevant logs/stack trace, name the single most likely cause, and explain it before editing.
FixApply the smallest change that addresses the cause — no drive-by refactors.
Regression-testAdd a test that fails before the fix and passes after; run the suite.
markdown
# skills/debug.SKILL.md  (project-specific — knows THIS repo)
## When to use: any failing test, error, or "it broke" report.

## Repro commands (edit per project)
- API:  `npm run test:api -- <spec>`   logs: `docker logs api --tail=100`
- Web:  `npm run dev` then reproduce in browser; check the console

## Loop — do not skip a step
1. REPRODUCE first. If you cannot reproduce, ask for exact steps. Never patch blind.
2. ISOLATE: read the trace, state the single most likely cause, wait for confirm.
3. FIX: smallest change only. No unrelated refactors.
4. REGRESSION: add a test that fails before / passes after. Run the full suite.

## Anti-patterns
# ❌ Changing several files at once "to be safe" — hides the real cause
# ❌ Removing the failing assertion instead of fixing the code

This is the pattern behind a real team debug skill (e.g. a Nibe_debug_skill tuned to that project's services and logs). Start from this skeleton, then edit the repro commands and log paths to match your stack — and commit it so the whole team debugs the same way.

05 — project vs global skills

Two places skill files live. For a team, only project/skills/ matters.

Project skills are git-tracked, team-shared, and active immediately for anyone who clones the repo. Global skills are per-developer-machine and require manual installation.

Propertyyour-project/skills/~/.claude/skills/
ScopeThis project onlyAll Claude Code sessions on that machine
Shared with teamYes — git-tracked, clone → readyNo — per developer machine, installed manually
How Claude reads itCLAUDE.md tells Claude when to read the fileAuto-discoverable via the Skill tool
Setup neededNone — part of the repo scaffoldEach developer installs manually

For a starter template, always use your-project/skills/. The moment someone clones the repo, the skill files are in place and CLAUDE.md is already wired to trigger them.

06 — do's and don'ts

Rules for writing effective skill files.

Skill files degrade in two ways: scope creep (one file covers too many concerns) and prose drift (tables replaced by paragraphs the AI misreads).

Do
One skill file per concern
Error handling is one file. Testing is another. Never mix them — the AI reads the entire file before the task and scope creep wastes context.
Do
Use decision tables over prose
The AI reads tables faster and misses less. Prose drifts; tables with scenario/class/HTTP columns do not.
Do
Include anti-patterns explicitly
"Never do X" blocks 80% of drift. The AI needs to know what NOT to do just as much as what to do.
Don't
Create skills for one-off patterns
Skills are for patterns repeated across multiple modules and sprints. A pattern used once belongs in a prompt, not a file.
Don't
Assume the AI infers from code
Even if the codebase uses the pattern consistently, write it down. The AI does not reliably infer conventions from existing code.
Don't
Let skills go stale
A stale skill file is worse than none — it actively instructs the AI to follow an outdated pattern. Update skills when patterns evolve.
Check your understanding
1. A vendor at capacity receives a new order request. According to TiffinConnect's error-handling skill, which exception should the service throw?
Correct.Not quite — the correct answer is highlighted above.
2. A developer asks the AI to write a Mongoose findById query and chain .exec() on it. Which Jest mock pattern from the unit-test skill applies?
Correct.Not quite — the correct answer is highlighted above.
3. A new developer joins TiffinConnect and clones the repo. Without any extra setup steps, which skill files are immediately available to them?
Correct.Not quite — the correct answer is highlighted above.