My Engineering Playbook: How I Build Scalable, Maintainable Software

A comprehensive walkthrough — assessing before coding, .NET Clean Architecture, React patterns, enterprise integration (SAP, Oracle, LDAP), project rescue, and BNM compliance. Interview-ready.

By Rais Helmy, IT consultant in Kuala Lumpur, Malaysia.

My Engineering Playbook. 6+ years of code that lasts.

How I assess a situation before touching code, implement .NET and React best practices, rescue failing projects, and deliver enterprise systems across insurance (Etiqa), defence (PDRM), and utility (TNB) domains in Malaysia.

career at a glance · 6+ years

  • Current Role: Sr .NET Developer - Etiqa Insurance · Clean Architecture · CQRS · BNM Regulated
  • Previous: Sr Technical Consultant - TNB ESS & TOMAS · SAP · FlutterFlow · .NET 6
  • Architecture: Solution Architect - PDRM C4i · ArcGIS · SIP/PBX · VMware HCI
  • Domains: Insurance · Defence · Utility - Etiqa · PDRM · TNB · Government
  • Core stack: .NET 8 · React · Flutter - SQL Server · Oracle · Cloudflare Workers
  • Known for: Project rescue specialist - Reverse-engineer, rebuild, ship under pressure

I never write line one before I understand the problem.

Whether it's a greenfield feature, a production bug at Etiqa, or an inherited codebase at TNB — I spend the first 20–30% of the effort just understanding context. What is the real problem? Who is affected? What does success look like? What exists already that I can extend instead of rewrite? At PDRM C4i, I spent two weeks producing HLD/LLD documentation before writing a single line of code. At TNB TOMAS, I spent the first sprint reverse-engineering a broken project before proposing my rebuild plan.

Questions I always ask first

What is the business outcome, not just the ticket? · Who are the stakeholders and what are their constraints? · What is the current system doing — trace it before changing it · What's the blast radius if this breaks? · Is there existing code or pattern that already solves 80% of this? · What regulatory or compliance requirements exist (BNM, PDRM)?

How I assess — real tools

Read the codebase before writing any code — grep, trace call stacks, git blame · Reproduce the bug or behaviour locally · Write down assumptions — validate with team + stakeholder · Sketch sequence diagrams for non-trivial flows · Check existing integration contracts (SAP, Oracle, LDAP) · Review change request history and regression patterns

→ My rule: if I cannot explain the problem in two sentences without jargon, I am not ready to implement. Ambiguous problems produce ambiguous solutions.

I inherited a broken project. I rebuilt it from scratch.

TNB TOMAS was an Asset & Permit Management System for Tenaga Nasional Berhad field engineers. When I joined, the project had broken source code, a non-functional mobile app, and no clear architecture. My first move was NOT to start coding — I spent the initial sprint performing a full reverse-engineering audit to diagnose why it was failing. Then I proposed and executed a complete rebuild.

What I did

Reverse-engineered the broken source code to understand original intent · Rebuilt mobile app from scratch using FlutterFlow + Flutter/Dart · Re-architected .NET 6 REST API with JWT auth + LDAP/AD SSO · Integrated SAP for asset master data sync · Designed multi-layer approval workflow engine · Delivered Asset, Permit, Health Monitoring, and Grid modules

Why it worked

Assessed before coding: spent a full sprint on diagnosis before proposing a plan · Clean separation: API ↔ Mobile ↔ SAP integration had clear boundaries · Workflow engine was configurable by role, group, asset category, and org hierarchy · iOS Enterprise + Android distribution via provisioning profiles · Direct stakeholder coordination with TNB operations team

→ Lesson: the temptation is to start fresh immediately. But if you don't understand why the previous attempt failed, you'll repeat the same mistakes with cleaner code.

.net best practice 1 · clean architecture + cqrs

Expectation: best practice

  • Strict inward dependency: Presentation → Application → Domain. Infrastructure implements Application contracts.
  • Commands mutate state. Queries read state. Never mix read/write in the same handler. This is how I structure Etiqa backend.
  • Domain layer has zero infrastructure dependencies — no EF Core, no HttpClient, no DI containers inside entities.

Reality: what most teams do

  • God controllers: 400-line action methods with EF queries, business rules, and email sending all mixed together.
  • Anemic domain models: entities are just data bags with getters/setters. All logic lives in "Service" classes.
  • DbContext injected directly into controllers — the domain has no boundary and the schema becomes the API contract.

Better approach (code)

// ✦ How I structure it at Etiqa — Command + Handler
public record ApproveClaimCommand(
    Guid ClaimId, Guid ApprovedBy
) : IRequest<Result>;

public class ApproveClaimHandler
    : IRequestHandler<ApproveClaimCommand, Result>
{
  public async Task<Result> Handle(
      ApproveClaimCommand cmd, CancellationToken ct)
  {
    var claim = await _repo.GetByIdAsync(cmd.ClaimId, ct);
    if (claim is null)
        return Result.Fail("Claim not found");

    claim.Approve(cmd.ApprovedBy); // domain logic
    await _repo.SaveAsync(ct);
    return Result.Ok();
  }
}

Common mistake (code)

// ✗ Fat controller — everything in one place
[HttpPost("{id}/approve")]
public async Task<IActionResult> Approve(Guid id)
{
  var claim = await _db.Claims
      .Include(c => c.Documents)
      .FirstOrDefaultAsync(c => c.Id == id);
  if (claim == null) return NotFound();

  // business logic in controller 🚩
  claim.Status = "Approved";
  claim.ApprovedAt = DateTime.UtcNow;
  await _db.SaveChangesAsync();
  await _emailSvc.SendApproval(claim); // 🚩
  return Ok();
}

.net best practice 2 · ddd + repository + unit of work

Expectation: best practice

  • Rich domain models: business rules live inside entities. Order.Approve() enforces invariants — not a service class.
  • Repository abstracts persistence. Application layer never writes SQL or references DbContext directly.
  • Unit of Work ensures transactional consistency across aggregate changes — one SaveChanges per business operation.

Reality: what most teams do

  • Domain models are just POCOs with public setters — any code can mutate state without validation.
  • Repositories that are just wrappers around DbContext.Set() — adding no value, just indirection.
  • Multiple SaveChanges calls in one request — partial failures corrupt business state.

Better approach (code)

// ✦ Rich domain with enforced invariants
public class Policy : AggregateRoot
{
  public PolicyStatus Status { get; private set; }
  public DateTime? RenewedAt { get; private set; }

  public Result Renew(DateTime effectiveDate)
  {
    if (Status != PolicyStatus.Active)
      return Result.Fail(
        "Cannot renew non-active policy"
      );

    Status = PolicyStatus.Renewed;
    RenewedAt = effectiveDate;
    AddDomainEvent(new PolicyRenewedEvent(Id));
    return Result.Ok();
  }
}

Common mistake (code)

// ✗ Anemic model — anyone can break rules
public class Policy
{
  public string Status { get; set; }
  public DateTime? RenewedAt { get; set; }
  // No validation — anyone writes anything
}

// business logic in a service
policy.Status = "Renewed"; // typo? "renewed"?
policy.RenewedAt = DateTime.Now; // local, not UTC 🚩

.net best practice 3 · structured logging + error handling

Expectation: best practice

  • Serilog with structured properties — every log has correlation ID, user context, and operation name queryable in Application Insights.
  • Global exception middleware returns ProblemDetails (RFC 7807) — no stack traces leak to clients.
  • Audit trail on every mutation: who, when, what changed. At Etiqa this is BNM-mandated.
  • AMLA watchlist batch jobs have separate logging pipelines with compliance-grade retention.

Reality: what most teams do

  • Console.WriteLine() and catch(Exception ex) { /* swallow */ } in production.
  • Inconsistent error formats: some endpoints return { error: "..." }, others return 500 with HTML.
  • No correlation ID — impossible to trace a single request across services.
  • Audit? "We'll add it later." (Later never comes.)

Example (code)

// ✦ Structured logging — Etiqa pattern
Log.Information(
    "Processing AMLA watchlist batch {BatchId} " +
    "for {ProfileCount} profiles",
    batch.Id,
    batch.Profiles.Count
);

// ✦ Global error middleware — ProblemDetails
app.UseExceptionHandler(appErr => {
    appErr.Run(async ctx => {
        ctx.Response.ContentType = "application/problem+json";
        var pd = new ProblemDetails {
            Status = 500,
            Title  = "An unexpected error occurred",
            Detail = "Ref: " + ctx.TraceIdentifier
        };
        await ctx.Response.WriteAsJsonAsync(pd);
    });
});

.net best practice 4 · api security · jwt + ldap

Expectation: best practice

  • JWT with proper claims — roles, permissions, and tenancy embedded. Refresh tokens stored securely, short-lived access tokens.
  • LDAP / Active Directory integration for enterprise SSO — I've done this at TNB TOMAS and PDRM C4i.
  • RBAC enforced at the API level — [Authorize(Roles = "...")] plus policy-based authorization for complex scenarios.

Reality: what most teams do

  • JWT tokens that never expire, stored in localStorage with no refresh rotation.
  • Username/password checked by querying DB on every request instead of validating a signed token.
  • Authorization checked in the UI only — backend endpoints accept anyone who sends the right JSON.

Better approach (code)

// ✦ JWT + LDAP integration (TNB TOMAS pattern)
public async Task<AuthResult> Authenticate(
    LoginDto login)
{
  // 1. Validate against AD/LDAP
  var ldapUser = await _ldapService
      .ValidateCredentials(
          login.Username, login.Password);
  if (!ldapUser.IsValid)
      return AuthResult.Fail("Invalid credentials");

  // 2. Map AD groups to application roles
  var roles = MapAdGroupsToRoles(ldapUser.Groups);

  // 3. Issue short-lived JWT + refresh token
  var token = _tokenService.GenerateJwt(
      ldapUser, roles, TimeSpan.FromMinutes(15));
  return AuthResult.Ok(token);
}

Common mistake (code)

// ✗ Auth in controller, no LDAP, long-lived token
[HttpPost("login")]
public IActionResult Login(LoginDto login)
{
  var user = _db.Users.FirstOrDefault(
    u => u.Name == login.User
      && u.Password == login.Pass // 🚩 plaintext!
  );
  if (user == null) return Unauthorized();

  var token = GenerateToken(user,
    TimeSpan.FromDays(365)); // 🚩 1 year!
  return Ok(new { token });
}

react best practice 1 · structure + state ownership

Expectation: best practice

  • One component, one responsibility. If a component has more than one reason to change, split it.
  • State lives as close to its consumers as possible. Lift only when two+ siblings genuinely share it.
  • Server state (API data) managed by React Query — never useState + useEffect + fetch chains.
  • Custom hooks extract domain logic, not just effects. If a hook only wraps useEffect, it's not abstracting enough.

Reality: what most teams do

  • 300-line "God components" that fetch data, compute derived values, handle forms, and render JSX all at once.
  • Global store holding UI state that belongs in local component state — a global "loading" flag for one button.
  • useEffect with empty deps as componentDidMount — masking missing dependency warnings.
  • Prop-drilling 4+ levels deep instead of composing with compound components or context for UI state.

Example (code)

// ✦ Focused components + React Query
function useOrderDetails(orderId) {
  return useQuery({
    queryKey: ['order', orderId],
    queryFn: () => api.orders.getById(orderId),
    staleTime: 1000 * 60 * 5,
  });
}

function OrderPage({ orderId }) {
  const { data, isLoading, error } = useOrderDetails(orderId);
  if (isLoading) return <OrderSkeleton />;
  if (error)     return <ErrorBoundary error={error} />;
  return <OrderDetails order={data} />;
}

// OrderDetails — pure render, no data fetching
function OrderDetails({ order }) {
  return (
    <section>
      <h2>{order.title}</h2>
      <OrderItems items={order.items} />
      <OrderTotal total={order.total} />
    </section>
  );
}

Scalability is not about handling 10× users. It's about handling 10× requirements.

The systems that fail at scale aren't necessarily slow — they're the ones where no one can change them safely anymore. At Etiqa, I maintain backend systems serving insurance lifecycle APIs under BNM regulation. At TNB, I inherited a monolith with thousands of users. The pattern is the same: tight coupling, missing abstractions, and logic scattered across layers make every new feature a risk. I design for changeability first, performance second.

What I enforce from day one

Dependency inversion — depend on interfaces, not concretions · Single Responsibility — every class/function does one thing well · Fail fast at boundaries — validate input at the edge, trust internal state · Explicit over clever — readable beats "elegant" one-liners · No premature abstraction — solve the actual problem, not the hypothetical one

Where codebases hit a wall

"Util" classes that become rubbish bins · Business logic scattered across controllers, services, and repositories · Missing boundaries — any module can call any other module · Tests that test implementation details, brittle to refactoring · Configuration hardcoded rather than externalised · "Don't touch that module" — untested undocumented debt

→ My measure: can a new developer make a change correctly without reading more than 3 files? If not, the boundary or naming is wrong.

clean code · naming + single responsibility

Expectation: best practice

  • Functions say what they do AND what they return: IsEligibleForDiscount(), CalculateRefundAmount().
  • Classes have one reason to change. OrderValidator does not send emails or write to the DB.
  • Magic values are named constants or enums — no hardcoded "3", "ACTIVE", or "0x02" in business logic.

Reality: what most teams do

  • ProcessData(), HandleRequest(), DoStuff() — names that describe nothing about what actually happens.
  • "Helper" classes that accumulate 40 unrelated methods spanning 5 domains.
  • if (status == 1 || status == 3 || type == "admin") — what does 1 mean? Why "admin"?

Better approach (code)

// ✦ Intention-revealing + single purpose
public class PolicyRenewalEligibilityChecker
{
  private const int MinActiveMonths = 6;

  public bool IsEligible(Policy policy)
  {
    return policy.Status == PolicyStatus.Active
        && policy.ActiveMonths >= MinActiveMonths
        && !policy.HasPendingClaims;
  }
}

// caller reads like English:
if (renewalChecker.IsEligible(policy))
    policy.Renew(effectiveDate);

Common mistake (code)

// ✗ Mystery names + side effects
public class Utilities
{
  public bool Check(Policy p)
  {
    if (p.S == 1 && p.M >= 6 && !p.PC)
    {
      SendEmail(p.Email); // 🚩 side effect in check!
      LogToDb("checked"); // 🚩 DB in a validator!
      return true;
    }
    return false;
  }
}

Integration is where most enterprise projects fail.

Across Etiqa, TNB, and PDRM, I've integrated with SAP HR/ERP, Oracle, SQL Server, LDAP/AD, Esri ArcGIS, PolisyM, MDM, SIP/PBX, XMPP/Jitsi, and VMS video systems. The pattern is always the same: never trust the external system's documentation. Always build a local integration test that proves the contract before writing business logic.

My integration discipline

Verify the real API contract — not the docs, the actual responses · Build adapter/gateway classes — isolate third-party APIs behind your own interface · Handle failures explicitly: SAP down? Queue the request. Oracle timeout? Retry with backoff · Log every external call with correlation ID, latency, and response status · Data mapping lives in one place — never scattered across multiple services

Systems I've integrated

SAP HR/ERP (TNB: employee data, payroll, asset sync) · Oracle + SQL Server (Etiqa: policy data, PolisyM, MDM) · LDAP/AD (TNB TOMAS + PDRM: SSO + RBAC) · Esri ArcGIS (PDRM: incident mapping, geospatial analytics) · SIP/PBX + XMPP/Jitsi (PDRM: emergency dispatch + comms) · VMS/RTSP (PDRM: CCTV live feeds)

→ Key: every external system gets its own adapter. Your domain never knows about SAP field names or Oracle column types. The adapter translates.

I architected a command centre for the Royal Malaysia Police.

PDRM C4i is a next-generation Command, Control, Communications, Computers & Intelligence platform covering real-time dispatch, GIS mapping, emergency telephony, unified comms, and video surveillance. I served as Solution Architect — responsible for the full system design from HLD/LLD to deployment on hyperconverged VMware ESXi infrastructure.

What I architected

.NET Core 5/6 API backend with RSS feed ingestion · Esri ArcGIS for live incident mapping and geospatial analytics · SIP/PBX telephony for emergency call routing · XMPP/Jitsi/Openfire for unified messaging + video · VMS with RTSP/MJPEG live feed streaming · Active Directory RBAC for all subsystems

Infrastructure I designed

Hyperconverged VMware ESXi — compute, storage, networking in HA cluster · VPN perimeter: IPSec (RadioIP) + OpenVPN + Softether · nginx + caddy reverse proxy with TLS termination · Security risk assessment + data retention policy · HLD/LLD documentation + architecture diagrams · Liaised directly with PDRM stakeholders for UAT + alignment

→ This project taught me that architecture documents are not bureaucracy — they're the only thing standing between your team and a 2am production call with stakeholders you can't explain things to.

real story · etiqa insurance — bnm compliance

Expectation: best practice

  • Engineered enterprise insurance backend using Clean Architecture + CQRS with MediatR — strict layer separation.
  • Built AMLA Watchlist Batch Job: automated pipeline fetching external watchlist, entity screening, sanction matching, and compliance audit trails.
  • User Profile Screening: real-time identity verification, risk flagging, role-based approval workflows.
  • Integrated SQL Server, Oracle, MDM, PolisyM — covering underwriting, endorsements, renewals, and claims lifecycle.

Reality: what most teams do

  • In regulated environments, "move fast and break things" gets you a BNM audit finding — not a feature release.
  • Every change goes through a structured CR process: impact assessment, regression test plan, UAT sign-off.
  • Audit logging is not optional — every mutation needs a who/when/what trail queryable by compliance team.
  • Zero-tolerance for partial deployments — you deploy the full CR or you roll back. No in-between.

Example (code)

// ✦ AMLA Watchlist Batch Job — Etiqa pattern
public class AmlaWatchlistJob : IScheduledJob
{
  public async Task ExecuteAsync(CancellationToken ct)
  {
    // 1. Fetch external watchlist source
    var watchlist = await _watchlistProvider
        .FetchLatestAsync(ct);

    // 2. Screen all active profiles
    var profiles = await _profileRepo
        .GetActiveProfilesAsync(ct);

    foreach (var profile in profiles)
    {
      var match = watchlist.Screen(profile);
      if (match.IsHighRisk)
      {
        await _flagService.FlagForReview(
            profile, match, ct);
        // 3. Compliance audit trail (BNM)
        _auditLog.LogScreeningResult(
            profile.Id, match, BatchId);
      }
    }
  }
}

mobile · flutterflow + flutter/dart

Expectation: best practice

  • Mobile architecture: clean separation between UI, state management, and API layer — even in FlutterFlow.
  • JWT token stored securely (FlutterSecureStorage, not SharedPreferences). Refresh token rotation on expiry.
  • Offline-first design for field engineering apps: queue operations when no connectivity, sync when back online.
  • iOS Enterprise + Android distribution: enterprise provisioning profiles, managed deployment pipelines.

Reality: what most teams do

  • Business logic in UI widgets — rebuilding the same validation in 5 different screens.
  • API calls scattered across widgets with no central error handling or retry logic.
  • Token stored in plain SharedPreferences — any rooted device can read it.
  • "Just upload to Google Drive" instead of proper enterprise distribution channels.

Better approach (code)

// ✦ TNB TOMAS — API service layer
class AssetApiService {
  final ApiClient _client;
  final TokenManager _tokens;

  Future<List<Asset>> getAssets() async {
    final response = await _client.get(
      '/api/assets',
      headers: _tokens.authHeaders,
    );
    return response.data
      .map((j) => Asset.fromJson(j))
      .toList();
  }
}

Common mistake (code)

// ✗ API call directly in widget build()
class AssetPage extends StatefulWidget {
  @override
  _State createState() => _State();
}
class _State extends State<AssetPage> {
  @override
  void initState() {
    http.get('https://api.tnb.com/assets',
      headers: {'token': prefs.getString('t')!}
    ).then((r) {
      setState(() { data = json.decode(r.body); });
    }); // No error handling 🚩
  }
}

databases · sql server + oracle + ef core

Expectation: best practice

  • Schema design with proper normalization, foreign keys, and indexes. Migration-first approach using EF Core migrations or Flyway.
  • AsNoTracking for read queries. Projection (Select) over loading entire entities. Pagination using cursor/keyset, not OFFSET.
  • Connection pooling configured properly. No DbContext leak across async boundaries.
  • Write operations use explicit transactions. Read-heavy paths hit read replicas where available.

Reality: what most teams do

  • SELECT * FROM everything WHERE something — no indexes, no projection, loading 50 columns to display 3.
  • N+1 queries: loop over orders, then for each order do a separate query for items.
  • String concatenation for SQL: $"WHERE name = '{input}'" — SQL injection waiting to happen.
  • One giant connection string with sa credentials, shared across all services.

Example (code)

// ✦ EF Core — projection + pagination
var policies = await _db.Policies
    .AsNoTracking()
    .Where(p => p.Status == PolicyStatus.Active)
    .OrderBy(p => p.CreatedAt)
    .Select(p => new PolicySummaryDto {
        Id = p.Id,
        Number = p.PolicyNumber,
        Premium = p.Premium
    })
    .Take(pageSize + 1) // cursor: fetch N+1
    .ToListAsync(ct);

var hasMore = policies.Count > pageSize;
if (hasMore) policies.RemoveAt(pageSize);

// ✗ What NOT to do
// var all = await _db.Policies.ToListAsync();
// return all.Skip(page * size).Take(size);
// ↑ loads ENTIRE table into memory 🚩

I've designed infrastructure from bare metal to edge serverless.

From hyperconverged VMware ESXi clusters at PDRM to Cloudflare Workers edge deployments for personal projects — I understand the full infrastructure spectrum. At PDRM, I designed HA clusters, VPN perimeters, and reverse proxy topology. At Etiqa, I work with Azure DevOps CI/CD. For my own platforms, I deploy serverless on Cloudflare Workers with D1 and R2.

Enterprise infrastructure

VMware ESXi: hyperconverged compute + storage + networking · VPN perimeter: IPSec, OpenVPN, Softether · Active Directory: RBAC, group policy, SSO federation · nginx + caddy: reverse proxy, TLS termination, load balancing · Docker: containerised .NET apps with multi-stage builds · GitLab CI/CD + Azure DevOps: pipeline automation

Edge & serverless

Cloudflare Workers: edge compute with sub-millisecond cold starts · D1: SQLite at the edge for globally distributed reads · R2: object storage for uploads and assets · Pages: static site deployment with CI from GitHub · Wrangler: local dev + deploy CLI · Zero infrastructure cost at idle — pay per request

→ The skill isn't in knowing one tool — it's in choosing the right one. PDRM needed on-premise HA. Etiqa needs regulated cloud. My sites need zero-cost edge. Different problems, different solutions.

technical skills matrix

  • .NET Ecosystem: .NET 6/7/8 · ASP.NET Core - Clean Architecture · CQRS · MediatR · DDD · EF Core · REST API
  • Mobile: FlutterFlow · Flutter · Dart - iOS Enterprise · Android · JWT · Secure Storage
  • Frontend: React · HTML/CSS/JS - React Query · Component composition · Cloudflare Pages
  • Databases: SQL Server · Oracle · PostgreSQL - D1 (edge SQLite) · Schema design · EF Core migrations
  • Integration: SAP · LDAP/AD · ArcGIS - PolisyM · MDM · SIP/PBX · XMPP/Jitsi · VMS/RTSP
  • Infrastructure: VMware · Docker · Cloudflare - nginx · VPN perimeter · GitLab CI · Azure DevOps

my checklist — before shipping any feature

  • Problem understood?: Explain in 2 sentences - Stakeholder + technical intent both clear before code
  • Existing code read?: Always first - Trace call stack, git blame, understand current state
  • Layer boundaries?: Domain logic in Domain - No EF/HTTP deps in domain. Clean Architecture enforced
  • Integration isolated?: Adapters for externals - SAP, Oracle, LDAP behind interfaces. Domain never knows
  • Logging + audit?: Structured from day 1 - Serilog, correlation ID, BNM audit trail, ProblemDetails
  • Tested + CR compliant?: UAT + regression before deploy - Impact assessed. Rollback plan documented. No partial deploy