Skip to content
~/rafael-ferreira

The Markmedi architecture: modular monolith, DDD and domain events

33 bounded contexts, Actions, enum state machines, ports and adapters and after-commit events: how I organized a large SaaS so that one person can maintain it.

Markmedi started as an online scheduling tool and today covers medical records, telemedicine with transcription, digitally signed prescriptions and medical certificates, CRM, automations, email campaigns, Google reputation, finance with health insurance billing (TISS, the Brazilian standard for exchanging data with health insurers), inventory and a patient portal. I'm the one who maintains all of it. The architecture has to answer a practical question: six months from now, when I open a module I haven't touched in a while, will I be able to change one rule without breaking another?

The answer I found is a modular monolith in Laravel, organized by domain, with explicit business rules and communication between modules through events.

Why a monolith

Microservices solve the problems of organizing large teams and scaling parts independently. I have neither. I would get all of the costs: coordinated deploys, eventual consistency across databases, distributed tracing, versioned API contracts between services I write myself. A well-divided monolith gives me database transactions that span modules when I need them (booking an appointment and reserving a room happen in a single transaction), a single deploy and refactorings the IDE can follow.

The discipline a distributed team enforces with network boundaries, I enforce with folder boundaries, conventions and tests.

One directory per context

All business code lives in app/Domain/<Context>. There are 33 bounded contexts and about 1,500 PHP files. The largest are Finance (with the TISS billing subcontext), Patient, Appointment, Billing, EmailMarketing, Clinic, Messaging and Prescription. Each context has its own folders of building blocks, and Laravel's app/Http/Controllers is practically empty.

Block

Files

Role

Controllers

240

HTTP only: validate, authorize, call an Action, return an Inertia page

Actions

237

One use case per class, with an execute() method

Requests

207

Input validation

Models

190

Persistence and relationships

Enums

149

States, types and allowed transitions

Services

95

Logic reused by several Actions

Policies

43

Per-resource authorization

Contracts

13

Ports to external services

Actions as the unit of business rules

Each use case is a small class with an execute() method: calculate available slots, check whether a time window is free, quote the price of an appointment, reschedule, start a visit. Controllers, jobs, scheduled commands and listeners call the same Action, so the rule exists in only one place. That also makes testing straightforward: in most cases I test the Action with the database and without HTTP.

Controller, job, scheduled command and listener call the same Action, which uses the context's models, enums and services

States live in enums with explicit transitions. An appointment's status, for example, knows which states it can move to:

enum AppointmentStatus: string
{
    // Scheduled, Confirmed, InProgress, Completed, Cancelled, NoShow

    public function canTransitionTo(self $next): bool
    {
        return match ($this) {
            self::InProgress => $next === self::Completed,
            self::Completed, self::Cancelled, self::NoShow => false,
            // ...
        };
    }
}

A late request that tries to confirm an appointment that is already completed runs into the enum, not into an if scattered across the controller.

Values that carry rules

Some concepts got their own type. Money is stored as integer cents through a cast, so 0.1 + 0.2 never shows up in a cash register closing. Dates are immutable (CarbonImmutable as the application default), which eliminates a whole family of bugs in scheduling math, where adding 30 minutes to a time slot must not change the original time. Phone numbers, SMS text, appointment price and arrival time have support classes with their own rules, and the data that crosses boundaries (a WhatsApp message, the result of a send, an automation graph) are immutable DTOs.

Ports and adapters for the outside world

Markmedi talks to WhatsApp, SMS, payment, AI, transcription, calendar and email providers. Each integration sits behind an interface in the context that uses it, and the concrete implementation is chosen in the container. WhatsApp has two real providers and an adapter that only writes to the log; SMS has two providers and the same log adapter; payment, AI and transcription also sit behind contracts.

The log adapter is used automatically when credentials are missing. In development, in tests and in review environments, no real message goes out to a patient by accident, and switching WhatsApp providers was a configuration change, not a refactoring.

The Action depends on an interface; the container picks the real provider, or the log adapter when credentials are missing

Domain events, always after commit

Modules communicate through events. When something relevant happens (an appointment is booked, confirmed or completed, a patient is registered, a deal is won in the CRM, a payment is recorded), the Action dispatches an event, and the other contexts react without the scheduling code having to know about finance or the CRM.

Every domain event implements ShouldDispatchAfterCommit. If the transaction rolls back, the event never happened. That detail prevents a particularly nasty class of bug: the listener that sends the patient a confirmation for an appointment that was never saved.

To give a sense of the reach, here is what happens when an appointment is completed:

  • the post-procedure instructions are published to the patient;
  • the CRM moves the contact forward in the funnel and records the session on the deal;
  • an NPS survey is created;
  • finance creates the receivable entry;
  • the health insurance claim form is issued, with its own retries;
  • if the procedure requires maintenance, the date of the next session is calculated;
  • the automations configured by the clinic are evaluated.

After commit, the appointment completed event is delivered to seven reactions in other contexts

Anything that can fail or take a while runs in queued listeners, with its own backoff; anything that has to be immediate runs synchronously. Completing an appointment doesn't wait for the claim form to be issued, and doesn't hang if the insurer's provider is down.

A generic listener for automations

Clinics build visual automations like "when the appointment is confirmed, wait 2 days and send a message". Instead of one listener per trigger, there is a single queued listener that subscribes to eight domain events and hands the event to the automation engine, which evaluates each flow's graph. Adding a new trigger means registering one more event on that listener and describing the context it provides.

Frontend: Inertia, Vue and typed routes

The frontend is Vue 3 with TypeScript, served through Inertia, so there is no internal REST API to maintain just for the dashboard. There are about 200 pages and 600 components, with a layer of base components and a layer of brand components. Backend routes and Actions are exposed to TypeScript by Laravel Wayfinder: when I rename a route or change a parameter, the frontend build flags the error before deploy. Backend routes are split into files by area (scheduling, finance, TISS, public), mirroring the contexts.

What I don't do

I don't use event sourcing. I have audit tables and domain events, which cover what I need (a history of who did what and decoupling between modules) without the cost of rebuilding state from events. I also didn't build generic repositories on top of Eloquent: models live in their contexts, and complex queries live in Actions or Services with business names.

Because an Action is the same for a controller, a job and a command, TDD comes naturally; I wrote about that in TDD and CI at Markmedi. Per-clinic data separation, which cuts across every context, is covered in multitenancy and security.

This post is part of the series about Markmedi.