0% found this document useful (0 votes)
2 views11 pages

Module 01 Notes

Module 01 focuses on establishing a reliable backend setup for a B2B multi-tenant application, emphasizing predictable startup, explicit configuration, and operational contracts. Key outcomes include a monorepo structure, environment files for configuration, a health check endpoint, and fail-fast validation for startup conditions. The module highlights the importance of clear contracts and separation of concerns to enhance debugging and future scalability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

Module 01 Notes

Module 01 focuses on establishing a reliable backend setup for a B2B multi-tenant application, emphasizing predictable startup, explicit configuration, and operational contracts. Key outcomes include a monorepo structure, environment files for configuration, a health check endpoint, and fail-fast validation for startup conditions. The module highlights the importance of clear contracts and separation of concerns to enhance debugging and future scalability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 01 Notes: Setup & Clean Code

1. Module Goal

This module solved the problem of unreliable backend setup. The goal was not just to make a server run, but to
make it start predictably, expose a stable operational contract, and fail fast when configuration is wrong.

What we shipped:

• a monorepo-based backend foundation

• an API app in `apps/api`

• `.[Link]` and `.env`

• startup validation for `PORT`

• a stable `GET /health` endpoint

• a full verify, break, fix, and reflect cycle

2. Product Scenario Chosen

Scenario chosen: `B2B Multi-Tenant`

Reason:

• one organization must never see another organization's data

• tenant separation is a hard requirement

• this pushes us to think about boundaries early

Meaning of tenant:

• a tenant is one customer organization using the same software platform

• example: different companies using the same SaaS product, but each company expects its own private data
space

Core rule:

• identify tenant context early

• carry tenant identity through every data access path

• never let CRUD, analytics, or caching ignore tenant scoping

3. Key Decision: Project Layout

Decision chosen: `B - monorepo`

Student reasoning summary:


• a single app becomes harder to manage as the system grows

• monorepo improves modularity

• monorepo makes it easier to add a worker later

Single App vs Monorepo

#### Option A: Single App

Pros:

• fastest to start

• fewer moving parts

• simpler deployment

Cons:

• harder to separate future services cleanly

• more risk of tightly coupled code

• config, startup, and feature logic can get mixed together

#### Option B: Monorepo

Pros:

• clear app boundaries

• easier to add future services like workers

• easier to share config helpers, types, and utility code

• scales better for multi-service evolution

Cons:

• more structure upfront

• more path and workspace indirection

• easier to make contract mismatches if each app is not explicit

Strong Viva Answer

Q: Why did you choose monorepo?

A:

I chose a monorepo because the system is expected to grow beyond a single process. A monorepo lets us keep
services separate while still sharing common code such as config helpers, validation logic, and types. It adds
some setup cost now, but it reduces long-term coupling and makes worker processes easier to introduce later.
4. What Is Clean Setup?

Clean setup means:

• the project structure is intentional

• configuration is explicit

• startup behavior is predictable

• operational routes are stable

• bugs are easier to locate because concerns are separated

This module connected setup quality to production reliability. A project is not "clean" just because folders look
neat. It is clean if a teammate can run it, understand it, and detect broken setup early.

5. Environment Files

Files created:

• `apps/api/.[Link]`

• `apps/api/.env`

Why `.[Link]` exists

`.[Link]` is a safe checklist of required environment variables. It documents the configuration contract of
the service without exposing real secrets.

Example values listed:

• `PORT=`

• `DATABASE_URL=`

• `MONGODB_URI=`

• `REDIS_URL=`

• `JWT_SECRET=`

• `API_KEY_A=`

• `API_KEY_B=`

Why `.env` exists

`.env` stores the real local runtime values for a specific machine or environment.

Example:

• `PORT=3000`

Why secrets should never go into git


• once committed, a secret can survive in history even if later deleted

• any clone or backup may preserve it

• leaked secrets stop being trustworthy

• rotation becomes mandatory and operationally expensive

Strong Viva Answer

Q: Why do we need both `.[Link]` and `.env`?

A:

`.[Link]` documents what configuration the application expects, while `.env` holds the real
environment-specific values used at runtime. This separation lets teammates set up the app safely without
exposing secrets in version control.

6. Fail Fast Configuration Validation

What problem it solves

Environment validation prevents the app from starting with invalid or missing configuration. It catches setup
mistakes immediately instead of allowing the system to run in a misleading or broken state.

What was validated

`PORT` had to:

• exist

• parse to a number

• be an integer

• be within the valid TCP port range

Why fail fast is better than silent defaults

If startup quietly chooses a default, the app may appear healthy while hiding a setup bug. That creates
inconsistent behavior across machines and makes debugging much harder later.

Example logic

Conceptually:

1. load `.env`

2. read `[Link]`

3. convert it to a number

4. reject invalid values

5. only then call `[Link](port)`

Strong Viva Answer


Q: What does fail fast mean?

A:

Fail fast means the process stops immediately when required startup conditions are not met. In this module, if
`PORT` was missing or invalid, the app refused to start instead of running with hidden configuration problems.

Q: Why is this a production-thinking concern and not just a coding style choice?

A:

Because predictable startup behavior affects deployment reliability, incident response, and operator confidence.
A service that starts with bad config can look alive while behaving incorrectly, which is more dangerous than
failing immediately.

7. Health Endpoint

Endpoint shipped:

• `GET /health`

Expected response:

{ "ok": true }

Why a health endpoint matters

A health endpoint is a small operational contract that answers one basic question: is the app up and responding?
It gives a fast, low-friction way to verify service availability.

Why it was isolated in a dedicated controller

The route was placed in a dedicated `HealthController` so that:

• operational behavior stays separate from business logic

• the route remains easy to test

• it does not get tangled with later features like create-link or redirect logic

Strong Viva Answer

Q: Why should `/health` stay simple?

A:

Because its job is operational visibility, not feature execution. If a health route depends on too much business
logic, it becomes harder to trust during debugging and deployments.

8. End-to-End Verification
Verification evidence used in the module:

• build passed

• app started successfully with valid config

• `GET /health` returned `200 OK`

• invalid `PORT` caused startup failure

• after fixing `PORT`, `GET /health` worked again

What end-to-end proof means here

It is not enough that one function looks correct in code. End-to-end proof shows:

• config is loaded

• startup succeeds

• route registration is correct

• the HTTP contract is reachable from the outside

Strong Viva Answer

Q: What evidence proved the implementation worked end to end?

A:

The evidence was that the service built successfully, started with valid configuration, and returned `200 OK` with
the expected payload from `GET /health`. We also proved the fail-fast path by breaking `PORT`, seeing startup
reject it, then restoring it and re-verifying the endpoint.

9. Break/Fix Incident

Symptom observed

• the server started

• `GET /health` returned `404 Not Found`

Initial debugging pattern

Good debugging flow:

1. reproduce the problem

2. form a hypothesis

3. run the fastest command to test that hypothesis

4. refine the theory when new evidence appears

5. confirm the fix with regression proof

Hypotheses considered
• route path changed

• controller or module registration broke

• a prefix like `/api` was added

• server was not actually listening

• watch mode was failing separately

Important distinction found

Two different issues appeared during investigation:

1. watch mode was failing with `spawn EPERM`

2. the actual app bug was a route contract mismatch

The real application bug:

• health endpoint existed at `/status`

• verification expected `/health`

Root cause

Route contract mismatch

This means the app still had a working route, but it no longer matched the expected public contract used by
verification and operations.

Fix applied

• changed route back from `/status` to `/health`

Regression proof

After the fix:

• app booted successfully

• route was mapped again at `/health`

• `GET /health` returned `200 OK` and `{ "ok": true }`

Strong Viva Answer

Q: What was the root cause of the bug?

A:

The root cause was a route contract mismatch. The application still had a health endpoint, but it was exposed at
`/status` while the expected contract and verification flow were using `/health`.

Q: What did the regression check prove?


A:

It proved that the fix restored the intended external contract. After changing the route back to `/health`, the
service started and the same verification request returned the expected successful response.

10. Monorepo Decision Callback

The module explicitly linked the break/fix lesson back to the project layout decision.

Because the student chose monorepo:

• the architecture gained modularity and future service separation

• but the extra indirection means each app can have its own config paths and route surfaces

• small mismatches can hide more easily if contracts are not explicit

The lesson:

• structure improves scale

• structure also increases the need for explicit contracts and verification

11. Security Preview from Module 01

Even though this was not the security module, one security idea already appeared:

• redirect endpoints can remain public for low-friction product use

• admin endpoints must be protected because they control data and system state

In a B2B multi-tenant system, this becomes even more important because protected routes must also enforce
tenant scoping.

Strong Viva Answer

Q: Why keep redirect endpoints public but admin endpoints protected?

A:

Redirect endpoints are part of the low-friction public behavior of the product, so they should be easy for end
users to access. Admin endpoints perform sensitive actions and can modify system state or expose private data,
so they must require authentication and tenant-aware authorization.

12. Risks and Mitigations

Risk

Contract drift between routes, modules, or services

Example:
• route implementation says `/status`

• verification and operators expect `/health`

Mitigation

• define explicit contracts

• centralize validation

• run repeatable regression checks against critical endpoints

Strong Viva Answer

Q: Name one risk from this module and one mitigation.

A:

One risk is contract drift, where the implemented route or behavior no longer matches what other parts of the
system expect. A mitigation is to keep contracts explicit and protect them with regression checks such as startup
verification and HTTP endpoint checks.

13. Likely Viva Questions With Model Answers

Conceptual

Q: What core problem did Module 01 solve?

A:

It solved unreliable backend setup by making startup predictable, configuration explicit, and the operational
contract verifiable. It also separated concerns so debugging and future feature work become safer.

Q: Which decision had the biggest impact, and why?

A:

The monorepo decision had the biggest impact because it shaped both the current project structure and the cost
of future change. It made worker separation and modular growth easier, while also increasing the need for
explicit contracts between parts of the system.

Q: Why is configuration validation part of clean code?

A:

Because clean code is not only about readable functions. It is also about building systems that fail in
understandable ways and behave consistently across environments.

Practical

Q: What files did you create for configuration?

A:
I created `.[Link]` to document required variables safely and `.env` to hold actual local runtime values
such as `PORT=3000`.

Q: What exact route did you expose for health checks?

A:

`GET /health`, returning `{ "ok": true }`.

Q: How did you verify startup validation?

A:

I broke the `PORT` value intentionally, restarted the app, and confirmed it failed immediately with a clear error.
Then I restored a valid port and confirmed the health endpoint responded successfully.

Debugging

Q: Why was the 404 not a startup failure?

A:

Because the server had started successfully. A `404` means the process is alive but the specific route contract
being requested is not registered at that path.

Q: What is the difference between a route bug and a process bug?

A:

A route bug means the app is running but the path or handler is wrong. A process bug means the service never
started or exited before it could accept requests.

Q: What did the `spawn EPERM` issue tell you?

A:

It showed that watch mode had an environment-specific process spawning problem, but it was separate from the
actual application route contract bug.

14. One-Page Revision Summary

• Scenario chosen: B2B multi-tenant

• Key requirement: one organization must not see another organization's data

• Layout decision: monorepo

• API app location: `apps/api`

• Config files: `.[Link]` and `.env`

• Critical validation: `PORT`

• Health contract: `GET /health` -> `{ "ok": true }`

• Verification method: build, start, curl, break config, restore, re-check

• Main break-step bug: route contract mismatch


• Fix: restore route from `/status` to `/health`

• Main lesson: explicit contracts and fail-fast startup make systems easier to debug and safer to grow

15. Commands Worth Remembering

npm run build


npm run start
[Link] [Link]

Failure drill concept:

• set invalid `PORT`

• restart app

• confirm clear startup failure

• restore valid `PORT`

• verify `/health` again

16. Best Study Takeaways

1. A backend foundation is not complete just because the server starts.

2. Configuration is part of the system contract.

3. Fail-fast validation is a production reliability tool.

4. Health endpoints are operational contracts.

5. Monorepos improve modularity but increase the need for explicit contracts.

6. A 404 can mean a path contract bug even when the app is healthy.

7. Always prove the fix with the same check that exposed the bug.

You might also like