1. Context and scale
A clinic booking system is a small transactional application with one correctness-sensitive operation: reserving a clinician’s time without double-booking it. Patients search availability and request appointments; clinic staff review schedules, cancel bookings, and handle exceptions. The system must preserve a reliable audit trail and protect sensitive information, but it does not need a distributed architecture to do so.
This blueprint uses one ASP.NET Core application, one PostgreSQL database, and a single Azure region. The application serves both the patient API and staff workflows. It uses PostgreSQL transactions and constraints for booking correctness, rather than relying on application-level checks alone.
Assumptions
These are sizing assumptions for an early clinic deployment, not measured capacity targets or Azure quotes.
| Dimension | Assumption |
|---|---|
| Users | Up to 1,000 daily users, including patients and clinic staff; 30 concurrent users during normal peaks |
| Requests | Average 0.5 requests/s, with short bursts up to 10 requests/s |
| Data volume | 100,000 appointments over three years; under 20 GB including indexes, audit events, and backups |
| Team size | Two engineers, with occasional product or operations support |
| Budget | Target a base infrastructure cost below roughly US$350/month before tax, support, and third-party email |
| Availability | Single-region service; planned maintenance is acceptable, but database backups and tested recovery are required |
| Retention | Appointment and audit retention are set by clinic policy and applicable law, not by this technical design |
The numbers deliberately describe a modest workload. A small app should not start with Kubernetes, a message broker, multiple independently deployed services, or a cache cluster. Each adds operational ownership before the workload justifies it.
The most important design choice is to make the database the final authority on appointment conflicts. A “check availability, then insert” sequence by itself is unsafe: two requests can both see the same open slot. The application can check availability for a helpful response, but a PostgreSQL constraint must settle the race.
2. Requirements
Functional requirements define what the clinic and patient can do. Non-functional requirements describe the qualities that make those actions safe and supportable.
Functional requirements
| Capability | Requirement | Initial implementation |
|---|---|---|
| Find availability | Patients can view available appointments for a clinician and date range | Query published availability and exclude active bookings |
| Book an appointment | An authenticated patient can request an available time | Transactional insert; database exclusion constraint prevents overlap |
| View appointments | Patients see their own bookings; staff can view clinic schedules | Role-based authorization and ownership checks |
| Cancel or reschedule | Patients or authorized staff can cancel; staff can arrange a replacement booking | Status transition recorded with actor and timestamp |
| Manage schedules | Staff can maintain clinician profiles and working availability | Staff-only API; changes audited |
| Notify users | Send a confirmation or cancellation notice | Write an outbox row in the booking transaction; deliver asynchronously |
| Record changes | Important actions are attributable and reviewable | Append-only audit records for sensitive state changes |
Do not treat an appointment as a complete medical record. Keep clinical notes, diagnoses, and treatment records out of this system unless they are explicitly in scope and the security, privacy, and regulatory design has been expanded to cover them.
Non-functional requirements
| Area | Initial target or constraint | Design response |
|---|---|---|
| Correctness | No overlapping active bookings for the same clinician | PostgreSQL range exclusion constraint |
| Latency | Most API requests should complete within 500 ms at this scale, excluding email delivery | Keep request paths synchronous only for booking persistence; measure database latency |
| Availability | A modest single-region service with documented recovery expectations | App Service plus managed PostgreSQL; no multi-region failover initially |
| Security | Protect personal information and prevent cross-patient access | TLS, authentication, authorization, private database networking, least privilege |
| Privacy | Collect only the data required to schedule care | Separate contact details from appointment facts; define retention with the clinic |
| Operability | A small team can deploy and diagnose the service | Structured logs, tracing, a small set of actionable alerts, automated deployment |
| Change safety | Schema changes must not break the running application | Expand-and-contract migrations; deploy compatible code before destructive changes |
| Recovery | Restore the database to a known point after operator error or data loss | Automated backups, documented retention, periodic restore exercise |
These are starting targets, not promises. Before production, the clinic should confirm user volumes, legal obligations, retention rules, recovery objectives, and acceptable downtime.
3. High-level design
The patient and staff clients call the same HTTPS API. Azure App Service runs the ASP.NET Core monolith. The app reads its database configuration from Key Vault, connects to Azure Database for PostgreSQL Flexible Server over private networking, and emits telemetry to Azure Monitor Application Insights.
An outbox table gives the application a durable boundary between booking and notification. The booking request commits the appointment and an outbox event together. A hosted worker claims pending outbox rows and calls the configured email provider. If the provider is unavailable, the booking remains committed and delivery can retry.
flowchart LR Patient["Patient browser or mobile client"] --> Api["ASP.NET Core minimal API on Azure App Service"] Staff["Clinic staff client"] --> Api Identity["Identity provider"] --> Api Api --> Db["Azure Database for PostgreSQL Flexible Server"] Api --> Vault["Azure Key Vault"] Api --> Email["Email provider"] Api --> Monitor["Azure Monitor and Application Insights"] Db --> Backup["Managed PostgreSQL backups"]
Caption: The small deployment keeps application logic in one service and delegates database operations and telemetry to managed Azure services.
The identity provider can be the clinic’s existing provider or a suitable managed identity product. The application maps the external subject identifier to an internal patient or staff record; it should not invent its own password storage. If the clinic uses an external identity system, confirm that its account recovery, MFA, and session policies meet the clinic’s needs.
The database should be reachable only through the app’s private network path. App Service regional VNet integration provides outbound connectivity from the app to a delegated PostgreSQL subnet. Key Vault stores secrets and supports managed identity-based access. Application Insights receives traces, metrics, and logs; avoid sending patient names, email addresses, appointment notes, or raw tokens into telemetry.
4. Cloud service mapping
The Azure column is the deployment in this blueprint. The other columns show comparable managed services, not drop-in replacements. Their networking, identity, pricing, and operational behavior differ.
| Component | Azure choice | AWS equivalent | GCP equivalent |
|---|---|---|---|
| Web/API hosting | Azure App Service for Linux | AWS App Runner or Elastic Beanstalk | Cloud Run |
| Relational database | Azure Database for PostgreSQL Flexible Server | Amazon RDS for PostgreSQL | Cloud SQL for PostgreSQL |
| Secret storage | Azure Key Vault | AWS Secrets Manager | Secret Manager |
| Application telemetry | Azure Monitor Application Insights | Amazon CloudWatch and AWS X-Ray | Cloud Monitoring and Cloud Trace |
| Private application-to-database path | App Service VNet integration and PostgreSQL delegated subnet | VPC networking for the application and RDS | VPC connector and private IP for Cloud Run and Cloud SQL |
| Identity | Clinic’s identity provider; optionally Microsoft Entra External ID for patient identities | Amazon Cognito or an existing OIDC provider | Identity Platform or an existing OIDC provider |
| CI/CD identity | GitHub Actions OIDC with Azure login | GitHub OIDC with an AWS IAM role | GitHub OIDC with Workload Identity Federation |
For this scale, a single App Service application and a managed PostgreSQL database are a useful division of responsibility: the team owns the application and schema, while Azure operates the host and database infrastructure. A separate frontend hosting service is optional; it is not required to make this architecture work.
5. Data design
The core model has patients, clinicians, appointments, and an outbox. Appointment records contain scheduling facts and references to the relevant people; they do not contain clinical notes. Audit records should capture significant changes without duplicating more personal data than necessary.
An appointment stores starts_at and ends_at as timestamptz values. The UI should present times in the clinic’s configured IANA time zone, while the API accepts an explicit offset and persists a normalized instant. A clinic should not silently assume that a patient’s device time zone is the clinic’s time zone.
erDiagram
PATIENT ||--o{ APPOINTMENT : books
CLINICIAN ||--o{ APPOINTMENT : attends
APPOINTMENT ||--o{ OUTBOX_MESSAGE : emits
PATIENT {
uuid id PK
text identity_subject UK
text display_name
text email
timestamptz created_at
}
CLINICIAN {
uuid id PK
text display_name
boolean active
}
APPOINTMENT {
uuid id PK
uuid patient_id FK
uuid clinician_id FK
timestamptz starts_at
timestamptz ends_at
text status
}
OUTBOX_MESSAGE {
uuid id PK
uuid appointment_id FK
text message_type
timestamptz created_at
timestamptz delivered_at
}Caption: The transactional model keeps booking ownership explicit and stores notification work beside the appointment that caused it.
The following DDL is a compact starting schema. Production migrations should be versioned and applied by the release process, not run opportunistically by every application instance.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE patients (
id uuid PRIMARY KEY,
identity_subject text NOT NULL UNIQUE,
display_name text NOT NULL,
email text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE clinicians (
id uuid PRIMARY KEY,
display_name text NOT NULL,
active boolean NOT NULL DEFAULT true
);
CREATE TABLE appointments (
id uuid PRIMARY KEY,
patient_id uuid NOT NULL REFERENCES patients(id),
clinician_id uuid NOT NULL REFERENCES clinicians(id),
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL,
status text NOT NULL CHECK (status IN ('booked', 'cancelled', 'completed')),
created_at timestamptz NOT NULL DEFAULT now(),
cancelled_at timestamptz,
CHECK (ends_at > starts_at),
EXCLUDE USING gist (
clinician_id WITH =,
tstzrange(starts_at, ends_at, '[)') WITH &&
) WHERE (status = 'booked')
);
CREATE INDEX appointments_patient_start_idx
ON appointments (patient_id, starts_at DESC);
CREATE INDEX appointments_clinician_start_idx
ON appointments (clinician_id, starts_at)
WHERE status = 'booked';
CREATE TABLE outbox_messages (
id uuid PRIMARY KEY,
appointment_id uuid NOT NULL REFERENCES appointments(id),
message_type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
delivered_at timestamptz,
attempts integer NOT NULL DEFAULT 0
);
CREATE INDEX outbox_pending_idx
ON outbox_messages (created_at)
WHERE delivered_at IS NULL;
The exclusion constraint uses half-open intervals: one appointment can end exactly when another begins, but two appointments cannot overlap. It applies only to booked rows, so a cancelled appointment releases its time. Keep status transitions explicit and test the constraint against concurrent requests. A constraint violation is a normal business conflict, not an unexpected server failure.
The outbox payload should contain only what the delivery worker needs. Consider storing an internal appointment identifier and resolving the recipient at send time, rather than copying a patient’s full profile into a queue-like table. Define deletion and retention behavior with the clinic; legal requirements can differ by jurisdiction.
6. Low-level design
Keep the monolith layered, but do not turn a small app into a framework project. Minimal API route groups define HTTP contracts; application services express booking rules; EF Core and Npgsql persist data; PostgreSQL constraints protect invariants that must survive concurrent requests.
classDiagram
class BookingEndpoints {
+CreateBooking(request)
+CancelBooking(id)
}
class BookingService {
+Book(command)
+Cancel(command)
}
class AppDbContext {
+DbSet~Appointment~ Appointments
+DbSet~OutboxMessage~ OutboxMessages
}
class Appointment {
+Guid Id
+Guid PatientId
+Guid ClinicianId
+DateTimeOffset StartsAt
+DateTimeOffset EndsAt
+string Status
}
class OutboxWorker {
+ProcessPending()
}
BookingEndpoints --> BookingService
BookingService --> AppDbContext
AppDbContext --> Appointment
BookingService --> OutboxWorkerCaption: The application service owns the booking use case, while the database remains the final authority on time conflicts.
Minimal runnable example
This complete example starts a minimal API with a health endpoint. It is intentionally not a booking implementation; it is a useful first deployment check for the runtime, routing, and health probe.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
app.Run();
Notice: Create a new ASP.NET Core minimal API project, replace its Program.cs with this code, and run it with dotnet run; then request /health.
Booking endpoint example
This example shows the important shape of the booking path: authenticated patient identity, server-side ownership, transaction, durable outbox write, and translation of PostgreSQL’s exclusion violation to HTTP 409. The entity and DbContext are abbreviated; the constraint is created by the migration shown earlier.
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Npgsql;
app.MapPost("/api/appointments", [Authorize] async (
CreateAppointmentRequest request,
HttpContext http,
AppDbContext db,
CancellationToken ct) =>
{
var subject = http.User.FindFirst("sub")?.Value;
if (string.IsNullOrWhiteSpace(subject))
return Results.Unauthorized();
if (request.EndsAt <= request.StartsAt)
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["endsAt"] = ["Must be later than startsAt."]
});
var patient = await db.Patients
.SingleOrDefaultAsync(x => x.IdentitySubject == subject, ct);
if (patient is null)
return Results.Forbid();
var clinicianIsActive = await db.Clinicians
.AnyAsync(x => x.Id == request.ClinicianId && x.Active, ct);
if (!clinicianIsActive)
return Results.NotFound();
var appointment = new Appointment
{
Id = Guid.NewGuid(),
PatientId = patient.Id,
ClinicianId = request.ClinicianId,
StartsAt = request.StartsAt.ToUniversalTime(),
EndsAt = request.EndsAt.ToUniversalTime(),
Status = "booked"
};
await using var transaction = await db.Database.BeginTransactionAsync(ct);
db.Appointments.Add(appointment);
db.OutboxMessages.Add(OutboxMessage.AppointmentBooked(appointment));
try
{
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
return Results.Created($"/api/appointments/{appointment.Id}",
new { appointment.Id, appointment.StartsAt, appointment.EndsAt });
}
catch (DbUpdateException ex) when
(ex.InnerException is PostgresException { SqlState: "23P01" })
{
await transaction.RollbackAsync(ct);
return Results.Conflict(new
{
title = "That clinician is no longer available at this time."
});
}
})
.RequireAuthorization()
.WithName("CreateAppointment");
Notice: The availability query is deliberately not used as a correctness check; concurrent requests are resolved by the exclusion constraint, and the outbox row commits only if the appointment commits.
For a production endpoint, validate allowed booking windows, clinic-local working hours, cancellation policy, idempotency behavior, and request size. Use a stable idempotency key if clients may retry after a network timeout: persist the key with the booking operation and return the original result for a repeated request. Avoid exposing whether an arbitrary patient identifier exists.
7. Key flows
The first flow covers the critical race: the application may show a slot as available, but PostgreSQL decides whether the booking is valid at commit time.
sequenceDiagram
actor Patient
participant Api as ASP.NET Core API
participant Db as PostgreSQL
Patient->>Api: POST appointment
Api->>Api: Authenticate and validate
Api->>Db: Begin transaction
Api->>Db: Insert appointment and outbox row
Db->>Db: Check exclusion constraint
alt Slot is available
Db-->>Api: Commit succeeds
Api-->>Patient: 201 Created
else Slot is already booked
Db-->>Api: Exclusion violation
Api-->>Patient: 409 Conflict
endCaption: The database constraint closes the race between availability checks and simultaneous booking requests.
The second flow shows why notification delivery is separate from booking success. A mail provider outage should not make a persisted appointment disappear or encourage a patient to submit a second booking.
sequenceDiagram
participant Worker as Outbox worker
participant Db as PostgreSQL
participant Mail as Email provider
Worker->>Db: Claim pending message
Db-->>Worker: Message and recipient data
Worker->>Mail: Send confirmation
alt Provider accepts
Mail-->>Worker: Accepted
Worker->>Db: Mark delivered
else Provider unavailable
Mail-->>Worker: Error or timeout
Worker->>Db: Increment attempts and release
endCaption: Delivery is retryable and independent of the patient-facing transaction, so a mail outage does not block booking.
Use bounded retries with exponential backoff and jitter. After repeated failures, move the message into an operationally visible dead-letter state or mark it for staff review. The worker should be idempotent where the provider supports idempotency keys, because a timeout can occur after the provider accepted the message but before the worker recorded success.
8. Build and release
Use infrastructure as code for the network, App Service, PostgreSQL, Key Vault, and monitoring configuration. The excerpt below shows the application and database resources while referring to network resources that should be provisioned by the same infrastructure stack. The delegated PostgreSQL subnet and private DNS zone must exist and be correctly linked before the server is created.
param location string = resourceGroup().location
param appName string
param postgresName string
param appSubnetId string
param postgresSubnetId string
param postgresPrivateDnsZoneId string
param databaseAdmin string
@secure()
param databaseAdminPassword string
resource plan 'Microsoft.Web/serverfarms@2022-09-01' = {
name: '${appName}-plan'
location: location
sku: {
name: 'S1'
tier: 'Standard'
capacity: 1
}
kind: 'linux'
properties: {
reserved: true
}
}
resource app 'Microsoft.Web/sites@2022-09-01' = {
name: appName
location: location
identity: {
type: 'SystemAssigned'
}
properties: {
serverFarmId: plan.id
httpsOnly: true
virtualNetworkSubnetId: appSubnetId
siteConfig: {
linuxFxVersion: 'DOTNETCORE|10.0'
alwaysOn: true
http20Enabled: true
}
}
}
resource postgres 'Microsoft.DBforPostgreSQL/flexibleServers@2022-12-01' = {
name: postgresName
location: location
sku: {
name: 'Standard_B1ms'
tier: 'Burstable'
}
properties: {
version: '16'
administratorLogin: databaseAdmin
administratorLoginPassword: databaseAdminPassword
delegatedSubnetResourceId: postgresSubnetId
privateDnsZoneArmResourceId: postgresPrivateDnsZoneId
publicNetworkAccess: 'Disabled'
storage: {
storageSizeGB: 32
}
backup: {
backupRetentionDays: 7
geoRedundantBackup: 'Disabled'
}
}
}
This is an illustrative resource excerpt, not a complete production module. Add the VNet and subnet definitions, private DNS zone and link, Key Vault, App Insights, database configuration, diagnostic settings, and deployment slot as appropriate. Pin and validate API versions against the target Azure environment before rollout. Do not place real credentials in source control or committed parameter files; use a secure deployment mechanism and rotate any bootstrap credential.
A practical release pipeline builds once, runs tests, publishes an artifact, and deploys that artifact. The example uses GitHub Actions and OIDC rather than a long-lived Azure service-principal secret.
name: clinic-api
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
id-token: write
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: 10.0.x
- run: dotnet restore
- run: dotnet test --no-restore --configuration Release
- run: dotnet publish src/Clinic.Api/Clinic.Api.csproj -c Release -o publish
- uses: actions/upload-artifact@v4
with:
name: clinic-api
path: publish
deploy:
if: github.event_name == 'push'
needs: test
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/download-artifact@v4
with:
name: clinic-api
path: publish
- uses: azure/login@v2
with:
client-id: ${{ vars.AZURE_CLIENT_ID }}
tenant-id: ${{ vars.AZURE_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
- uses: azure/webapps-deploy@v3
with:
app-name: ${{ vars.AZURE_WEBAPP_NAME }}
package: publish
Add a migration step before traffic is shifted to newly deployed code. For a small system, a controlled one-off migration job can run the migration bundle using a restricted identity and network path. Prefer additive changes first: add nullable columns or new tables, deploy code that can use them, backfill if required, then remove old structures in a later release. Do not make every app instance race to apply schema migrations at startup.
Test strategy
| Test type | What to verify | Practical approach |
|---|---|---|
| Unit | Validation, status transitions, authorization decisions, retry policy | Fast tests with a test clock and fake notification sender |
| Integration | EF mappings, migrations, constraints, transaction behavior | Run PostgreSQL in Testcontainers; test concurrent overlapping inserts |
| Contract | Request and response shapes, status codes, error format | OpenAPI checks and client-facing API tests |
| Load | Booking bursts, search queries, connection pool behavior, outbox throughput | Test against a production-like database tier and realistic appointment distributions |
A mocked database cannot prove an exclusion constraint works. Keep a focused integration test that submits two overlapping bookings concurrently and asserts one succeeds while the other receives a conflict. Load tests should also include normal read traffic, not only a synthetic booking storm.
9. Observability
Observability must help a small team answer four questions quickly: is the API reachable, are bookings succeeding, is PostgreSQL slowing down, and are notifications accumulating? Collect enough context to diagnose those questions without copying sensitive patient information into logs or traces.
Structured logging
Log request outcome, route template, status, duration, trace ID, and a non-sensitive correlation identifier. Avoid logging request bodies, authorization headers, email addresses, names, or raw SQL parameters containing personal data.
{
"timestamp": "2026-11-02T10:15:30.152Z",
"level": "Information",
"event": "appointment_created",
"appointment_id": "a5d34d14-8f26-4984-9b48-e52f4f235bc1",
"clinician_id": "f3d91ad1-c6a5-4a9b-975e-008eef34ee91",
"result": "created",
"duration_ms": 84,
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"
}
Treat identifiers as potentially sensitive. Use them only where operationally justified, restrict log access, and set retention according to the clinic’s policy. Do not log a patient ID merely because it is convenient.
RED and USE metrics
For the API, use RED: rate, errors, and duration. For infrastructure, use USE: utilization, saturation, and errors. Keep metric labels bounded; do not use patient, appointment, or clinician identifiers as metric dimensions.
| Signal | Metric examples | What it tells the team |
|---|---|---|
| RED: rate | Requests per second by route template and method | Whether traffic has changed or requests are not reaching the app |
| RED: errors | 5xx rate, booking conflicts, validation failures | Whether the service is failing, and whether expected business conflicts are increasing |
| RED: duration | p50, p95, p99 API duration | Whether user-visible latency is degrading |
| USE: CPU | App Service CPU utilization and PostgreSQL CPU | Whether compute is becoming constrained |
| USE: memory | App process memory and database memory pressure where available | Whether the app is approaching resource limits |
| USE: saturation | App instance queue or HTTP queue, database connections, storage growth | Whether capacity is being exhausted before outright failure |
| USE: errors | Database connection failures, throttling, storage or backup failures | Whether the managed resource is failing or rejecting work |
Instrument ASP.NET Core and Npgsql with OpenTelemetry, then export through the Azure Monitor exporter. Add a custom activity around the booking use case so traces have a useful business-level span without attaching patient data.
using System.Diagnostics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var activitySource = new ActivitySource("Clinic.Booking");
builder.Services.AddSingleton(activitySource);
builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService("clinic-api"))
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddNpgsql()
.AddSource("Clinic.Booking")
.AddAzureMonitorTraceExporter(options =>
{
options.ConnectionString =
builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
}));
// In the booking service:
using var activity = activitySource.StartActivity("booking.create");
activity?.SetTag("booking.outcome", "accepted");
The example assumes the Azure Monitor OpenTelemetry exporter and ASP.NET Core, HTTP client, and Npgsql instrumentation packages are included. Confirm package compatibility with the chosen .NET and Npgsql versions. Keep span attributes low-cardinality and non-sensitive; do not attach request bodies, email addresses, or patient identifiers.
SLI and SLO
| Service-level indicator | Initial objective | Measurement window |
|---|---|---|
| API availability | 99.5% of valid health checks return successfully | Rolling 30 days |
| API latency | 95% of non-reporting API requests complete within 500 ms | Rolling 30 days |
| Booking correctness | Zero confirmed overlapping active appointments | Continuously; investigate every violation |
| Booking request success | At least 99% of valid booking attempts finish without an unexpected server error | Rolling 30 days |
| Notification freshness | 95% of confirmation messages are accepted by the provider within five minutes | Rolling 30 days |
A conflict response is not a service failure. Report it separately from unexpected 5xx errors, and do not set an SLO that pressures the team to accept invalid bookings.
Dashboards and alerts
Build one dashboard with API request rate, 4xx/5xx rates, latency percentiles, booking outcomes, database CPU and connections, database storage, outbox backlog age, and deployment markers. A second operational view can show backup status and recent restore-test results.
Page an on-call engineer for sustained elevated 5xx rates, failed database connectivity, exhausted database connections, or a growing outbox backlog that threatens the notification freshness objective. Notify the team without paging for isolated booking conflicts, ordinary validation failures, or one transient provider timeout. Tune thresholds against real baselines after launch.
10. Security and compliance
This app handles personal information even if it does not store clinical notes. Security decisions should be reviewed with the clinic’s privacy, legal, and compliance owners; a cloud service choice by itself does not establish compliance with any particular regulation.
- Authentication: Use a standards-based identity provider. Require MFA for staff where supported, and use short-lived tokens with appropriate audience and issuer validation.
- Authorization: Enforce patient ownership on every appointment read and write. Apply staff permissions through explicit policies; do not trust a client-supplied patient ID.
- Network access: Disable public access to PostgreSQL and use private networking from App Service. Restrict administrative access and avoid broad firewall rules.
- Secrets: Use managed identity to read Key Vault references. Rotate database credentials and deployment credentials; never commit secrets or print them in pipeline logs.
- Transport and storage: Require TLS for application and database connections. Use managed encryption at rest and confirm the selected service configuration and key-management requirements.
- Data minimization: Store only scheduling and contact data needed for the workflow. Keep clinical records out of scope and avoid sensitive data in logs, traces, and analytics.
- Auditability: Record sensitive staff actions and appointment state changes with actor, timestamp, and operation. Restrict access to audit data and prevent ordinary application paths from modifying historical events.
- Application security: Validate inputs, protect administrative routes, set appropriate CORS rules, use rate limits for authentication-sensitive endpoints, and keep dependencies patched.
- Operational access: Apply least privilege to developers, the app’s managed identity, database migration jobs, and the CI/CD identity. Review access periodically.
- Compliance work: Confirm data residency, retention, deletion, breach response, vendor agreements, and the clinic’s obligations with qualified stakeholders before production use.
11. Cost
The following is an assumption-based monthly estimate for one modest production environment in one Azure region. It is a planning range, not a price quote; region, pricing plan, storage, backups, traffic, support, and tax can materially change the result. Check the current Azure pricing calculator and regional service availability before committing.
| Component | Assumption | Approximate monthly range |
|---|---|---|
| App Service plan | One Linux Standard S1 instance, always on | US$70–120 |
| PostgreSQL Flexible Server | Small burstable instance, 32 GB provisioned storage, no high availability | US$50–140 |
| Backups and storage overhead | Short retention, within modest data volume | US$5–25 |
| Key Vault | Low request volume and a small set of secrets | US$1–10 |
| Application Insights and logs | Low event volume with sampling and retention limits | US$5–40 |
| Networking and DNS | VNet, private DNS, and associated low-volume services | US$0–30 |
| Email provider | Low-volume transactional mail; provider-dependent | US$0–30 |
| Estimated total | Excludes tax, support plans, and engineering time | US$131–395 |
The range exceeds the stated target at its upper end because telemetry ingestion, region, and database pricing are variable. Keep the first deployment simple, but do not save money by making the database public or omitting backups. Review actual billing after the first full month and adjust service tiers based on measured CPU, connections, storage, and latency.
For a non-production environment, use smaller tiers and shut down resources when practical. Do not let development and test deployments silently inherit production-sized capacity. Conversely, do not reduce production capacity below what the clinic’s confirmed recovery and availability requirements support.
12. Failure modes, resilience and disaster recovery
| Failure mode | User impact | Response |
|---|---|---|
| Two patients book the same clinician and time | One request must fail cleanly | Exclusion constraint allows one commit; return HTTP 409 for the loser |
| PostgreSQL is unavailable | Booking and schedule reads fail | Return a controlled 503, keep timeouts bounded, alert on connectivity, do not claim success |
| Email provider is down | Appointment exists but notice is delayed | Retry outbox messages with backoff; show the booking in the patient’s account |
| App deployment fails | New version may not serve traffic | Use a deployment slot where available; health-check before swap and roll back if needed |
| Migration is incompatible | Old or new app version may fail against schema | Use additive migrations, test against a restored copy, and separate destructive changes |
| Accidental deletion or corruption | Records may be lost or inconsistent | Use managed backups and point-in-time recovery; document restore steps and access controls |
| App instance restarts | In-flight request may be interrupted | Clients use idempotency keys for retries; persisted transactions determine actual outcome |
| Region becomes unavailable | Service may be unavailable for an extended period | Accept single-region recovery initially; document restore and redeployment steps before promising an RTO |
A small system can have resilient behavior without multi-region infrastructure. The immediate priorities are bounded timeouts, database constraints, idempotent retries, automated backups, and a restore procedure that someone has actually tested.
Set recovery point and recovery time objectives with the clinic. A seven-day backup retention assumption is not a recovery objective, and a backup that has never been restored is not a verified recovery plan. Run a periodic restore into an isolated environment, validate schema and representative records, and record the elapsed recovery time. If the clinic requires shorter recovery time or negligible data loss, the database availability and backup design must change.
13. Evolving to the next scale
Scale in response to measured constraints and changed requirements, not because a small application might someday become large. The monolith remains a sound choice while one team can deploy it safely and the database can handle its workload.
| Trigger | First change | Avoid doing prematurely |
|---|---|---|
| App CPU or request queue is persistently high | Increase App Service capacity or add an instance; verify session state is not held in memory | Splitting APIs into services before profiling |
| Database CPU, connections, or query latency is high | Inspect query plans and indexes, tune pool limits, then scale the database tier | Adding Redis before identifying the expensive query or consistency need |
| Notifications compete with API work | Move outbox processing to a separate worker process or managed queue | Making email delivery part of the booking transaction |
| Reporting degrades booking performance | Use read-optimized queries, scheduled exports, or a separate reporting store | Running broad analytical scans on the booking database without limits |
| One deployment becomes risky for multiple teams | Introduce clearer module boundaries and independent ownership | Microservices that share tables and require coordinated releases |
| Recovery requirements increase | Add database high availability or a tested regional recovery design | Claiming multi-region readiness without rehearsed failover |
| Traffic becomes geographically distributed | Evaluate regional application instances and a consciously designed data strategy | Active-active writes to appointments without conflict semantics |
The first scaling move is usually vertical: a larger app or database tier, followed by query and connection-pool tuning. Add application instances only after confirming that the app is stateless, scheduled jobs are safe across instances, and the outbox worker uses database-backed claiming such as FOR UPDATE SKIP LOCKED.
If a second worker is introduced, keep the outbox as the durable source of pending work and make claims transactional. A managed queue can later decouple delivery, but it introduces another system to observe and recover. Move only when the operational benefit outweighs that cost.
14. Phased implementation plan
A two-person team can deliver this in phases, but dates depend on identity setup, clinic policy decisions, and external review. Treat each phase as a deployable increment with a clear acceptance criterion.
- Confirm scope and policy. Agree on appointment states, clinician scheduling rules, cancellation behavior, identity provider, data retention, privacy requirements, recovery objectives, and who can access staff functions. Keep clinical records explicitly out of scope unless separately designed.
- Create the foundation. Provision the development environment through infrastructure as code: App Service, PostgreSQL, private networking, Key Vault, and telemetry. Establish OIDC deployment, database migration conventions, and CI checks.
- Build the booking slice. Implement patient and clinician records, authenticated booking, cancellation, the PostgreSQL exclusion constraint, and an integration test for competing bookings. Publish an OpenAPI contract and test the API against a real PostgreSQL instance.
- Add the operational workflow. Implement staff schedule views, outbox processing, email retries, audit events, and a basic dashboard. Define log redaction and alert ownership before production traffic.
- Validate failure behavior. Test unavailable database and email provider behavior, duplicate client retries, incompatible migrations, backup restore, and deployment rollback. Run a representative load test and record a baseline.
- Launch narrowly. Start with one clinic or a controlled patient group. Review booking conflicts, latency, error rates, support cases, outbox age, and billing. Adjust SLOs and capacity from observed behavior.
- Expand deliberately. Add features or capacity only when the clinic’s workflow or measured system limits require them. Revisit identity, retention, disaster recovery, and audit access as the user base and regulatory context evolve.
The architecture’s success criterion is not the number of Azure services it uses. It is whether patients can book reliably, clinic staff can operate the schedule, sensitive data stays controlled, and a small team can understand and recover the system when something goes wrong.
This article was generated with AI. #AIGenerated