Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Modeling

The Modeling section focuses on transforming real-world requirements into structured software systems.

Unlike the Algorithm section, these exercises are not primarily about finding one optimal algorithm.

The objective is to identify and model:

  • entities
  • relationships
  • validation rules
  • data sources
  • queries
  • commands
  • state transitions
  • inventories
  • reservations
  • schedules
  • resource allocation
  • transactions
  • priorities
  • failures
  • recovery
  • history
  • domain invariants

The section contains:

14 tasks

The exercises begin with focused domain models and gradually progress toward systems containing many interacting entities, limited resources, state machines, schedules, network relationships, and operational workflows.

The final tasks approach the complexity of small backend systems rather than isolated programming exercises.

Modeling Principles

Separate Domain Entities

Different real-world concepts should normally be represented independently.

For example:

Candidate
Developer
DevOps

or:

Hospital
Patient
Doctor
Admission
Surgery

or:

PowerPlant
Generator
Substation
TransmissionLine
ConsumerRegion

or:

Airport
Aircraft
Flight
Passenger
Gate
Runway

A separate model is useful when a concept has its own:

identity
data
relationships
lifecycle
rules
behavior

The purpose is not to create as many structures as possible.

The purpose is to represent the domain clearly.

Reuse Shared Information

When several entities share information, unnecessary duplication should be avoided.

Examples include:

Person
├── Coach
└── Client

or:

MedicalStaff
├── Doctor
└── Nurse

The exact implementation may use:

composition
embedding
inheritance where appropriate
traits
interfaces

or another equivalent technique.

The important requirement is consistency.

Model Relationships Explicitly

Real systems are networks of related entities.

Simple examples:

Training -> Coach
Training -> Client

Concert -> Artist
Concert -> Stage

Larger systems contain deeper relationships:

Region
  -> DataCenter
    -> Rack
      -> Server
        -> ServiceReplica

or:

Hospital
  -> Department
    -> Ward
      -> Room
        -> Bed
          -> Admission
            -> Patient

or:

PowerPlant
  -> Generator
    -> TransmissionNetwork
      -> Substation
        -> ConsumerRegion

References should be validated instead of assuming that every referenced entity exists.

Separate Queries from Commands

Queries retrieve information.

Commands modify state.

For example:

search medicine

does not modify inventory.

purchase medicine

does.

Likewise:

search available hotel rooms

does not create a reservation.

create reservation

does.

And:

get account balance

does not change financial state.

create transfer

does.

This distinction becomes increasingly important as system complexity grows.

Preserve Source Data

Several tasks use external data sources such as:

JSON
YAML
CSV
custom structured text

A recommended processing flow is:

Raw Data
   |
   v
Parser
   |
   v
Validation
   |
   v
Domain Models
   |
   v
Domain Processing

Business logic should operate on validated domain models rather than directly on raw file representation.

Validate Domain Rules

Modeling is not only about defining structures.

The implementation must protect important rules.

Examples include:

candidate must satisfy mandatory requirements

training must reference an existing coach

stock must not become negative

hardware components must be compatible

server capacity must not be exceeded

vehicle capacity must not be exceeded

hotel rooms must not be double-booked

one hospital bed cannot contain two patients

one operating room cannot host overlapping surgeries

transmission-line capacity must not be exceeded

refunds must not exceed captured payments

one aircraft cannot operate overlapping flights

Invalid input should be distinguishable from a valid request that simply produces no result.

Model State Explicitly

Many entities have lifecycles.

For example:

Shipment:

created
  -> reserved
  -> packed
  -> dispatched
  -> delivered

or:

Admission:

requested
  -> admitted
  -> discharged

or:

Payment:

created
  -> authorized
  -> captured
  -> settled

or:

Flight:

scheduled
  -> boarding
  -> departed
  -> in_flight
  -> landed
  -> completed

State should not be changed arbitrarily.

Valid transitions should be explicitly defined.

Distinguish Desired State from Current State

Some systems contain both:

what should exist

and:

what currently exists

For example:

Desired Replicas = 6
Running Replicas = 5

or:

Regional Demand = 180 MW
Supplied Power  = 150 MW

The difference between desired and current state may trigger recovery or corrective operations.

Model Time and Intervals Carefully

Many tasks depend on time.

Examples include:

appointments
staff shifts
maintenance windows
production deadlines
flight schedules
hotel reservations
authorization expiration

Time intervals should have clearly defined boundaries.

Scheduling systems should explicitly detect overlapping intervals.

Model Priority

Some systems cannot process every request equally.

Examples include:

emergency triage
shipment priority
production priority
critical electricity consumers
flight operational priority

Priority rules should be explicit and deterministic.

Model Resource Allocation

Later tasks contain many limited resources.

Examples include:

medicine stock
hardware stock
server CPU and memory
vehicle capacity
hotel rooms
hospital beds
operating rooms
medical equipment
raw materials
production machines
electrical generation
transmission capacity
airport gates
runways
account balances

Where applicable, distinguish:

total
available
reserved
allocated
consumed
released

Model Network Constraints

Several tasks contain graph-like physical or logical networks.

Examples include:

service dependencies
logistics routes
power transmission
airport routes

An important distinction is:

resource exists

versus:

resource can reach the required destination

The Energy Grid task makes this distinction particularly important.

Total generation may exceed total demand while a region still experiences a local deficit because network capacity or topology prevents delivery.

Preserve History

Current state alone is often insufficient.

Larger systems may need to preserve:

what happened
when it happened
which entity changed
why it changed
what caused the change

Examples include:

shipment tracking events
server migration history
patient medical history
grid operational events
production history
flight events
hotel stay history
financial ledger entries
audit events

Historical information should remain stable even after current state changes.

Model Failure and Recovery

Real systems contain failures.

Examples include:

server failure
failed delivery
room maintenance
medical equipment failure
doctor unavailability
generator failure
transmission-line failure
machine failure
aircraft failure
declined payment

The implementation should model both:

failure

and:

what happens after failure

Recovery may involve:

migration
retry
redelivery
room reassignment
patient transfer
power rerouting
load shedding
rework
rebooking
diversion
reversal
refund

Preserve Atomic Operations

Some state changes affect multiple entities and must behave as one logical operation.

Examples:

reserve all required materials or none

reserve all requested hotel rooms or none

allocate patient and bed consistently

debit one account and credit another account

create all required replica placements or reject deployment

Failed operations should not leave partially modified state.

Support Idempotency

Large systems may receive the same command more than once.

Important operations may therefore contain:

RequestID

Processing the same request twice must not duplicate its effect.

Examples include:

deployment creation
shipment creation
hotel reservation
patient admission
medication administration
grid failure report
bank transfer
refund

Protect Domain Invariants

Some rules must always remain true.

Examples:

stock >= 0

allocated resources <= total resources

one room cannot have overlapping active reservations

one hospital bed cannot have two active patients

one doctor cannot participate in overlapping procedures

generator output <= available generation capacity

transmission flow <= line capacity

storage energy >= 0

accepted production + rejected production <= produced quantity

available account balance >= 0

refund total <= captured amount

one aircraft cannot operate overlapping flights

These invariants should be tested directly.

Keep Processing Deterministic

When several valid choices exist, define deterministic behavior.

Examples:

lowest ID first
earliest deadline first
highest priority first
lowest price first
lexicographical ordering

Identical input should produce identical results.

Task 1 — Technical Candidate Qualification

Create models for:

Developer
DevOps

and determine whether candidates satisfy mandatory technical requirements.

Main topics:

  • shared candidate information
  • role-specific data
  • validation
  • qualification rules
  • missing-requirement reporting

This task introduces domain entities and rule-based evaluation.

Task 2 — Gym Training Management

Create a gym training system containing:

Coaches
Clients
Training Sessions
Exercise Sets
Schedules

Main topics:

  • shared person data
  • entity relationships
  • ID-based references
  • lookup operations
  • state updates
  • referential validation

This task introduces a central model connected to several independent entities.

Task 3 — Music Festival Management

Create a festival system containing:

Concerts
Artists
Stages
Equipment
Staff
Guards

Data is loaded from several external sources.

Main topics:

  • multi-entity modeling
  • external data
  • parsing
  • relationships
  • joining independent datasets

Task 4 — Exchange Office Network

Create two currency exchange markets and process exchange requests.

Main topics:

  • typed currencies
  • exchange rates
  • account sectors
  • market comparison
  • transaction processing
  • logging
  • structured output

This task introduces transactional processing and mutable account state.

Task 5 — Medicine Store Network

Create two medicine markets supporting:

search
filtering
price comparison
purchase
stock updates
partial purchase

Main topics:

  • catalog modeling
  • query criteria
  • purchasing
  • inventory
  • best-match selection
  • query versus command behavior

Task 6 — Hardware Store Search Engine

Create a three-market hardware system containing:

CPU
Motherboard
GPU
RAM
PowerSupply
PcCase
Cooler
SSD

Main topics:

  • heterogeneous entities
  • large datasets
  • multi-market inventory
  • compatibility
  • filtering
  • configuration building
  • purchasing
  • delivery processing

This is the first large marketplace-style modeling exercise.

Task 7 — Infrastructure Resource Orchestrator

Create an infrastructure orchestration system containing:

Regions
Data Centers
Racks
Servers
Tenants
Services
Deployments
Replicas
Quotas
Placement Rules
Health Checks
Maintenance
Migrations

Main topics:

  • hierarchical infrastructure
  • resource allocation
  • desired versus current state
  • placement constraints
  • quotas
  • failure recovery
  • migration
  • health
  • audit history
  • idempotency

Task 8 — Logistics and Shipment Processing Network

Create a logistics system containing:

Customers
Warehouses
Packages
Shipments
Vehicles
Drivers
Routes
Delivery Attempts
Tracking Events
Returns

Main topics:

  • physical location
  • shipment lifecycle
  • capacity
  • driver eligibility
  • routing
  • tracking
  • failed delivery
  • redelivery
  • returns
  • history

Task 9 — Hotel and Reservation Network

Create a hotel network containing:

Hotels
Rooms
Room Types
Guests
Reservations
Stays
Payments
Services
Housekeeping
Maintenance
Employees
Invoices

Main topics:

  • availability
  • time intervals
  • overlapping reservations
  • multi-room booking
  • pricing
  • promotions
  • check-in
  • check-out
  • room reassignment
  • housekeeping
  • maintenance
  • billing
  • occupancy
  • idempotency

This task focuses on keeping commercial reservations and physical room operations consistent.

Task 10 — Banking and Payment Processing Platform

Create a banking and payment platform containing:

Customers
Accounts
Balances
Cards
Merchants
Transfers
Payments
Authorization Holds
Captures
Settlements
Refunds
Fees
Limits
Fraud Rules
Disputes
Ledger Entries
Statements

Main topics:

  • exact monetary representation
  • balances
  • ledger modeling
  • transfers
  • authorization
  • holds
  • capture
  • settlement
  • refunds
  • reversals
  • limits
  • fraud decisions
  • disputes
  • reconciliation
  • financial invariants
  • idempotency

Task 11 — Healthcare and Hospital Management Network

Create a healthcare network containing:

Hospitals
Departments
Wards
Rooms
Beds
Patients
Doctors
Nurses
Appointments
Emergency Cases
Admissions
Diagnoses
Treatments
Medications
Laboratory Tests
Medical Equipment
Operating Rooms
Surgeries
Transfers

Main topics:

  • patient lifecycle
  • medical history
  • appointment scheduling
  • staff scheduling
  • emergency triage
  • priority processing
  • bed allocation
  • medical equipment
  • surgery scheduling
  • resource conflicts
  • hospital capacity
  • patient transfer
  • failure recovery
  • idempotency

This task introduces scarce-resource scheduling where emergency priority may require explicit changes to an existing plan.

Task 12 — Energy Grid and Power Distribution Network

Create an electrical power network containing:

Power Plants
Generators
Substations
Transformers
Transmission Lines
Consumer Regions
Critical Consumers
Energy Storage
Demand
Generation
Failures
Maintenance

Main topics:

  • network topology
  • generation and demand
  • capacity
  • power allocation
  • transmission bottlenecks
  • reserve generation
  • energy storage
  • generator failure
  • line failure
  • overload
  • rerouting
  • grid islanding
  • load shedding
  • critical consumers
  • restoration
  • operational history

This task introduces a distributed resource network where having enough total capacity does not guarantee that the resource can reach every destination.

Task 13 — Manufacturing and Production Line Management

Create a manufacturing system containing:

Factories
Production Lines
Machines
Products
Bills of Materials
Raw Materials
Workers
Work Orders
Production Batches
Quality Checks
Warehouses

Main topics:

  • bill of materials
  • material reservation
  • production planning
  • scheduling
  • machine availability
  • worker skills
  • quality control
  • rework
  • scrap
  • inventory
  • machine failure
  • production history

This task models the complete transformation from raw material to finished product.

Task 14 — International Airport and Air Traffic Network

Create a transportation network containing ten airports.

The system includes:

Airports
Terminals
Gates
Runways
Airlines
Aircraft
Flights
Passengers
Baggage
Cargo
Pilots
Cabin Crew
Fuel
Maintenance
Weather
Air Traffic Sectors

Main topics:

  • graph relationships
  • scheduling
  • interval conflicts
  • resource allocation
  • passenger connections
  • baggage transfer
  • cargo
  • crew constraints
  • maintenance
  • weather
  • delay propagation
  • cancellation
  • rerouting
  • holding
  • diversion

This is the final and broadest Modeling task.

It combines many concepts introduced throughout the section into one interconnected transportation network.

Progression

The fourteen tasks gradually increase in domain size and behavioral complexity.

Conceptually:

Task 1
Domain entities and validation

        ↓

Task 2
Relationships and state updates

        ↓

Task 3
Multiple entities and external data

        ↓

Task 4
Transactions and account state

        ↓

Task 5
Search, purchasing, and inventory

        ↓

Task 6
Large marketplace and compatibility

        ↓

Task 7
Infrastructure allocation and recovery

        ↓

Task 8
Stateful logistics lifecycle

        ↓

Task 9
Reservation intervals and hotel operations

        ↓

Task 10
Financial lifecycle and ledger consistency

        ↓

Task 11
Healthcare scheduling and emergency priority

        ↓

Task 12
Distributed network capacity and recovery

        ↓

Task 13
Manufacturing and production planning

        ↓

Task 14
Large transportation and air-traffic network

The progression is not based only on the number of models.

Each stage introduces additional forms of interaction:

relationships
state
external data
inventory
transactions
resource allocation
time
priority
scheduling
networks
failure
recovery
history
atomicity
idempotency
domain invariants

Modeling vs Algorithms

The Algorithm section mainly asks:

How should this data be processed?

The Modeling section additionally asks:

What entities exist?

What information belongs to each entity?

How are entities related?

What state does the system maintain?

Which operations are queries?

Which operations are commands?

Which state transitions are legal?

Which resources are limited?

How are resources reserved and released?

How does priority affect processing?

How does network topology affect availability?

What happens when an operation fails?

How does the system recover?

Can the operation be safely retried?

What history must be preserved?

Which invariants must always remain true?

A correct output alone is therefore not enough.

The structure and consistency of the solution are part of the exercise.

Language Independence

The tasks are language-independent.

They may be implemented using:

Go
Rust

or another suitable language.

Different languages provide different modeling mechanisms.

For example:

Go:
structs
interfaces
composition

Rust:
structs
enums
traits
composition

The exercises describe domain behavior rather than requiring one specific object-oriented technique.

Suggested Architecture

The larger tasks naturally benefit from separation of responsibilities.

A conceptual architecture may look like:

Input / External Data
        |
        v
Parsing and Validation
        |
        v
Domain Models
        |
        v
Repositories / Stores
        |
        v
Domain Services
        |
        +-- Queries
        +-- Commands
        +-- Validation
        +-- Scheduling
        +-- Priority
        +-- Allocation
        +-- State Machines
        +-- Network Processing
        |
        v
State Changes
        |
        +-- Resource Updates
        +-- Inventory Updates
        +-- Financial Updates
        +-- Operational Updates
        |
        v
History / Audit / Ledger

This architecture is not mandatory.

The important goal is to avoid placing unrelated responsibilities into one oversized model or function.

Testing

Each task should test both successful and unsuccessful behavior.

Useful categories include:

  • valid model creation
  • invalid references
  • successful queries
  • empty query results
  • successful commands
  • failed commands
  • invalid state transitions
  • inventory changes
  • resource exhaustion
  • capacity conflicts
  • time conflicts
  • priority ordering
  • network disconnection
  • file parsing
  • failure handling
  • recovery
  • atomic operations
  • duplicate requests
  • history generation
  • domain invariants

For state-changing operations, tests should verify both returned result and final system state.

For operations affecting several entities, verify that all related state remains consistent.

Examples:

failed material reservation
must not reserve only part of the required material

failed multi-room reservation
must not reserve only some requested rooms

failed patient admission
must not occupy a bed without creating the admission

failed bank transfer
must not debit only the source account

failed grid reroute
must not leave transmission flow above capacity

Goal

The goal of the Modeling section is to practice turning real-world requirements into understandable and internally consistent software systems.

A successful solution should make it clear:

  • what entities exist
  • what information they own
  • how they are related
  • what operations are available
  • which operations modify state
  • which rules protect the domain
  • how state changes over time
  • how priority affects decisions
  • how resources are allocated
  • how network topology affects availability
  • how failures are represented
  • how recovery works
  • how duplicate commands are handled
  • how history is preserved
  • which invariants must always remain true

The later tasks intentionally resemble small backend and operational systems rather than isolated programming exercises.

The objective is not to reproduce production-scale healthcare, electrical-grid, manufacturing, aviation, banking, or infrastructure platforms.

The objective is to practice the modeling decisions that make complex systems understandable, testable, deterministic, and internally consistent.

Scalionix Docs

Keyboard Shortcuts

Navigate the documentation without leaving the keyboard.
Navigation
Previous subject
←
Next subject
→
Previous subsection
Alt + ↑
Next subsection
Alt + ↓
Interface
Documentation Home
Ctrl + Enter
Search
Alt + Q
Open shortcuts
?
Close dialog
Esc
Scalionix Docs

Search Documentation