Skip to content

Interactive engineering lab

Small lessons pulled from my own projects. The code is copyable, and the demos run in your browser, no server involved.

(01)Java

Model the domain with records

Records give you immutable data with equals, hashCode and toString for free. Keep behaviour that belongs to the data right next to it.

Attendance.java
public record Attendance(long employeeId, Instant checkIn, Instant checkOut) {

    public Duration worked() {
        if (checkOut == null) return Duration.ZERO; // still checked in
        return Duration.between(checkIn, checkOut);
    }
}

// Total hours across a week, using streams
Duration total = week.stream()
        .map(Attendance::worked)
        .reduce(Duration.ZERO, Duration::plus);

(02)Spring Boot

A thin controller over a service

Controllers translate HTTP; services hold the rules; repositories talk to the database. Validation happens at the edge with @Valid.

EmployeeController.java
@RestController
@RequestMapping("/api/v1/employees")
public class EmployeeController {

    private final EmployeeService service;

    public EmployeeController(EmployeeService service) {
        this.service = service;
    }

    @GetMapping("/{id}")
    public EmployeeDto get(@PathVariable long id) {
        return service.findById(id); // throws 404 if missing
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public EmployeeDto create(@Valid @RequestBody CreateEmployee req) {
        return service.create(req);
    }
}

(03)React

State in, UI out

Store the minimum state and derive the rest. This one is live, try it.

check-in-demo.tsx
export function CheckInDemo() {
  const [log, setLog] = useState<Entry[]>([]);
  const checkedIn = log.at(-1)?.type === "in"; // derived, not stored

  const toggle = () =>
    setLog([...log, { type: checkedIn ? "out" : "in", at: new Date().toLocaleTimeString() }]);

  return <button onClick={toggle}>{checkedIn ? "Check out" : "Check in"}</button>;
}

Status

Checked out

  • No events yet.

(04)Next.js

App Router architecture

Server components by default, client components only where interaction lives. This very site follows this layout.

project structure
app/
├── layout.tsx            // shared shell: nav, theme, fonts
├── page.tsx              // server component: no JS shipped unless needed
├── projects/
│   ├── page.tsx          // static list
│   └── [slug]/page.tsx   // generateStaticParams → prerendered at build
└── api/
    └── attendance/route.ts  // server-only route handler

// Rule of thumb: render on the server, add "use client" only where
// the component needs state, effects or browser APIs.

(05)SQL

Queries that answer real questions

A late-arrivals report joins attendance, employees and branches. And row-level security makes the database itself enforce tenant isolation.

late_arrivals.sql
-- Who checked in late today, per branch
SELECT b.name            AS branch,
       e.full_name       AS employee,
       a.check_in::time  AS checked_in
FROM attendance a
JOIN employees e ON e.id = a.employee_id
JOIN branches  b ON b.id = e.branch_id
WHERE a.check_in::date = CURRENT_DATE
  AND a.check_in::time > b.shift_start + INTERVAL '10 minutes'
ORDER BY b.name, a.check_in;
tenant_isolation.sql
-- Each company only ever sees its own rows
ALTER TABLE attendance ENABLE ROW LEVEL SECURITY;
ALTER TABLE attendance FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON attendance
  USING (company_id::text = current_setting('app.company_id', true));

(06)REST API

Requests and responses

Try the verbs below. Status codes carry meaning: 201 on create, 204 on delete, 422 on invalid input.

request
GET /api/v1/employees
response
[
  {
    "id": 1,
    "name": "Asha",
    "role": "employee"
  },
  {
    "id": 2,
    "name": "Ravi",
    "role": "team_lead"
  }
]

Simulated in your browser. No real API is called.

(07)System design

Geofenced attendance, end to end

The check-in flow from EMAS: the client sends its location, the server computes the distance to the branch and decides. Move the employee around to see the rule in action.

office

distance = haversine(office, employee)

50 m

✓ Check-in allowed

EMAS architecture: web and mobile clients call a FastAPI backend backed by PostgreSQL and Redis.Web dashboardNext.js · ReactMobile appCapacitor · Android/iOSREST APIFastAPI · PythonPostgreSQLrow-level securityRedisrate limitingHTTPS + JWTSQL
High-level overview

(08)AI engineering

Vision models, with guardrails

An experiment from my AI support agent work: ask a local model what's in a photo, then verify before answering. Shown as code only, nothing runs here.

identify.ts
// Ask a local vision model (via Ollama) to describe a product photo
const res = await fetch("http://localhost:11434/api/generate", {
  method: "POST",
  body: JSON.stringify({
    model: "llava",
    prompt: "What product is in this photo? Reply with brand and model only.",
    images: [base64Image],
    stream: false,
  }),
});
const { response } = await res.json();
// Never trust it blindly: verify against OCR text and the catalogue first.

And here is the decision rule that sits after the model, simplified and playable:

combined confidence

71

Not sure yet. “Could you take a closer photo of the label or model sticker?”