Tenafriqv2.0 · Q2 2026

Tenafriq System
Microservice Architecture

Resident · Facility · Workforce · Inventory · POS · Supply Chain
Core Domain: tq_core7 ServicesEvent‑Driven · Cloud‑Native
OVERVIEW
Executive Summary

Tenafriq is a microservice ecosystem designed to unify property management, access control, equipment logistics, workforce orchestration, inventory, point‑of‑sale, and supply chain. The platform serves thousands of concurrent residents, staff, and POS terminals with strict consistency requirements and real‑time hardware integration.

📊 Peak Throughput
6,200 req/s (POS + checkout heavy hours). p95 latency < 120ms for core reads, < 400ms for writes.
🏷️ Availability
99.95% monthly SLA. Degraded modes for facility access & equipment checkouts.
⚙️ Design tenets
Shared‑nothing per service, asynchronous integration for long‑running ops, strong data ownership.
SYSTEM ARCHITECTURE
High‑Level Topology
            graph TD
              Client["Web/Mobile/POS Terminal"]
              APIG["API Gateway (Kong)"]
              Services["resident-core | facility-access | equipment-checkout | workforce-mgmt | inventory-core | pos | supply-chain"]
              CorePkg["tq_core (shared pip package)"]
              DB[("PostgreSQL Cluster")]
              Cache[("Redis Cluster")]
              MQ[("RabbitMQ")]

              Client -->|HTTPS + JWT| APIG
              APIG -->|proxy + auth| Services
              Services -->|import| CorePkg
              Services --> DB
              Services --> Cache
              Services -->|async events| MQ
              MQ -.-> Services
          
Figure 1: All traffic enters via API Gateway. Services embed tq_core for auth, config, logging. Async events (stock depletion, late fees, shift swaps) flow through RabbitMQ.

The gateway terminates TLS, validates JWT (using tq_core's verification), and applies per‑service rate limits. Each service owns its database schemas, while Redis provides distributed locks (locker codes, inventory holds) and session storage for suspended POS transactions.

FOUNDATION
Shared Core: tq_core

tq_core is a pip‑installable Python package pinned to a single version across all services. It provides common infrastructure to reduce duplication and guarantee consistency.

ModuleResponsibility
core.configPydantic settings loader with env overrides for each service
core.authJWT creation/validation, bcrypt hashing, permission helper (RBAC)
core.dbAsync SQLAlchemy engine, session + transaction middleware
core.middlewareRequest ID, structured logging, global error handling
core.eventsTyped event publisher (RabbitMQ) with retry logic
core.models.baseBase ORM (UUID, soft‑delete, optimistic lock version)
core.schemasPydantic v2 pagination, audit fields, common DTOs
Versioning discipline Breaking changes require major version bump + migration guide; services pin exact version in pyproject.toml.
DOMAIN SERVICES
Service‑by‑Service Architecture
🏠 resident-core

Manages leases, rent/fee payments, maintenance requests, referrals, community boards, and unit/floor inventory. Slow‑changing compliance data, high legal integrity.

MethodEndpointDescription
POST/leases/{id}/payRecord rent payment (idempotent key)
GET/maintenance/requestsList with filters (unit, status)
POST/referralsResident referral tracking
🔓 facility-access

Real‑time concurrency for locker/spots, event bookings, QR/card check‑in, membership management, hardware integration (door readers, smart locks).

Redis distributed locks guarantee single active reservation for lockers; stale locks expire after 30s.
🛠 equipment-checkout

Checkout/return with due dates, late fees, maintenance status, and reservation holds. High transactional volume (gym gear, AV equipment).

EndpointDescription
POST /checkoutReserve + mark out, decrement available stock
👥 workforce-management

Complex rules engine: shift scheduling, timecard with rounding, time‑off requests, drop/pick shifts, min/max hour enforcement, audit trail for labor laws.

📦 inventory-core

Product catalog, tax categories, discounts (cart/product), stock levels, low‑stock alerts. Source of truth for all items sold via POS and used in supply chain.

💳 point-of-sale (POS)

High‑throughput, stateful cart sessions. Suspend/resume with recall ID, barcode scan → add to cart, dynamic offer application, shift/day closing with financial reconciliation.

🚚 supply-chain & stock

Vendor management, auto‑PO generation based on reorder points, stock inbound/outbound, receiving validation, integration with distributor APIs.

SECURITY
Authentication & Authorization
            sequenceDiagram
              participant C as Client
              participant G as API Gateway
              participant A as auth-service (internal)
              participant Core as tq_core
              participant S as Target Service

              C->>G: POST /auth/login (email/password)
              G->>A: forward
              A->>Core: verify_password()
              Core-->>A: valid
              A->>Core: create_access_token()
              Core-->>A: JWT
              A-->>G: tokens
              G-->>C: access/refresh tokens

              C->>G: GET /residents (Bearer)
              G->>S: forward with token
              S->>Core: decode+verify JWT, extract user
              Core-->>S: UserContext
              S->>S: RBAC check (role: resident/staff/manager)
              S-->>G: response
              G-->>C: data
          
Figure 2: tq_core provides unified JWT handling; auth‑service is a thin wrapper over the core package. Every service validates tokens locally without extra network calls.
MESSAGING
Sync vs Async & Event Bus

Read‑heavy operations use synchronous gRPC/HTTP calls with < 50ms budget. State changes that require cross‑service consistency (e.g., stock reservation → inventory update) are event‑driven via RabbitMQ.

            graph LR
              POS[POS Service] -->|reserve items| Inventory[Inventory Core]
              Inventory -->|StockLevelChanged| MQ[RabbitMQ]
              MQ --> SupplyChain[Supply Chain]
              MQ --> FacilityAccess[Facility Access]
              FacilityAccess -->|checkout complete| Equipment[Equipment Checkout]
          
Figure 3: Typical event cascade after POS checkout – inventory adjustments, reorder checks, and locker releases.
STORAGE
Data Ownership & Consistency
Database strategy
Each service owns dedicated PostgreSQL schemas. Cross‑service reads use eventual consistency through materialized views or API calls. The shared Redis cluster caches rate limits, JWT revocation, and session data.
Eventual consistency boundaries
POS "suspend" cart → stored in Redis with TTL. Late fee calculation runs as a scheduled job reading from resident‑core and equipment‑checkout.
OPS
Kubernetes Deployment
            graph TD
              Ingress["Ingress (nginx)"]
              GW["API Gateway Pods (3 replicas)"]
              NS["tenafriq Namespace"]
              SVC1["resident-core (HPA: 5-20)"]
              SVC2["facility-access (HPA: 3-15)"]
              DBCluster["StatefulSet PostgreSQL + read replicas"]
              RedisCluster["Redis Sentinel"]
              MQCluster["RabbitMQ quorum queue"]

              Ingress --> GW
              GW --> SVC1 & SVC2
              SVC1 --> DBCluster
              SVC2 --> RedisCluster
          
Figure 4: Horizontal Pod Autoscaler based on CPU/memory + custom metrics (queue length for POS). Each service has resource requests (0.5 CPU / 512Mi) and limits.
ServiceReplicas (min/max)CPU req/limitMemory
resident-core4/150.6 / 2.01Gi / 2Gi
pos-service6/250.8 / 2.51.5Gi / 3Gi
supply-chain2/100.5 / 1.51Gi / 2Gi
TOOLING
Technology Stack
CategoryChoiceJustification
API FrameworkFastAPI (Python 3.11+)Async native, Pydantic v2, automatic OpenAPI
Shared Librarytq_core (private PyPI)Zero‑copy auth, config, DB session reuse across 7 services
DatabasePostgreSQL 15 (asyncpg)ACID, JSONB for flexible attributes, row‑level locking
Message BrokerRabbitMQ (mirrored queues)Reliable delivery, dead‑letter for retries
CacheRedis 7Rate limiting, distributed locks, POS cart state
API GatewayKong (PostgreSQL backend)JWT validation, rate limiting, plugin extensibility
OrchestrationKubernetes (EKS/AKS)Auto‑scaling, self‑healing, rolling updates
ObservabilityOpenTelemetry + Prometheus + GrafanaTrace propagation, custom metrics (checkout latency, stock events)
Cross‑Cutting Concerns

This section is a stub. Once the following information becomes available, it will cover:

  • Distributed tracing policy with OpenTelemetry sampling (1% for reads, 100% for checkout/POS transactions)
  • Centralized secret management (HashiCorp Vault) and rotation strategy
  • Global rate limiting per resident tier and per IP for public endpoints
  • Audit trail design for financial operations and workforce timecards
Security Deep Dive
  • TLS 1.3 end‑to‑end between clients and API gateway, mTLS between services using Istio or linkerd.
  • JWT short lifetime (15 min) + refresh token rotation stored in Redis.
  • RBAC model: resident, staff, facility manager, admin. API Gateway rejects unauthorized requests.
  • Network policies: deny ingress between services except via gateway and internal event bus.
Failure Mode Analysis
FailureProbabilityImpactMitigation
PostgreSQL primary outageLowHigh (all writes)Automated failover to replica (< 60s), read replicas serve queries during switch
facility-access service crashMediumMedium (no new check‑ins)Circuit breaker, local hardware cache (offline QR mode via sync token)
RabbitMQ queue backpressureMediumMediumDead‑letter queues, backpressure triggers autoscaling of consumers, alert on queue depth >10k
POS suspend session lossLowLowPersist cart state to Redis with replication + hourly backup snapshot
Distributed lock deadlock (locker)LowLowRedlock algorithm with fallback TTL (30s), manual unlock endpoint for staff
Open Questions & Roadmap

This section is a stub. Once the following information becomes available, it will cover:

  • Multi‑region deployment strategy for diaspora or large portfolio of properties
  • Offline capability for facility doors and POS during WAN outage
  • Integration with third‑party ERP for accounting (QuickBooks / SAP)
  • Data retention policy for workforce timecards (7 years compliance)
⸻ ⸻ ⸻