BosskuAI Software Architecture
Use this skill when the main question is structural — where does this belong, how should components relate, and what are the long-term consequences of this design?
How this differs from nearby skills
bosskuai-code-revamp: executes a structural change once the direction is decided; this skill decides what the direction should be.
bosskuai-codebase-analysis: orients you in an unfamiliar codebase; load first if the current structure is unclear before making architectural recommendations.
bosskuai-engineering-delivery: implements the chosen architecture; this skill decides what to build.
bosskuai-rigorous-code-review: reviews a specific diff; this skill reviews the structural design that diff embodies.
Mindset
- The best architecture decision is usually the smallest commitment that preserves future optionality.
- Coupling is the enemy — hidden coupling is the worst kind.
- Read the code before making structure claims. Docs are aspirational; code is actual.
- Non-functional requirements (scalability, availability, consistency, latency) constrain structure more than feature requirements do.
Architectural lenses to apply
Apply whichever are relevant; skip clearly irrelevant ones:
Layering and responsibility
- Is logic in the right layer (presentation, application, domain, infrastructure)?
- Is there leakage across layer boundaries (UI calling DB directly, domain importing HTTP)?
- Is the domain model anemic (no behavior) or over-entangled (too many dependencies)?
Module and service boundaries
- Does each module have a single clear owner and a stable public contract?
- Are bounded contexts explicit (DDD) or implicit and blurry?
- Where is the coupling highest? Is it necessary or accidental?
Data ownership and consistency
- Who owns each piece of data? Can two services write to the same record?
- Is eventual consistency acceptable, or is strong consistency required?
- Are CQRS or event sourcing patterns appropriate, or over-engineering for the current scale?
- For each shared write, which guard holds it: a transaction, a row lock, a unique constraint or an idempotency key? A write with no guard is a race.
Integration and external dependencies
- Are external integrations behind abstraction boundaries (anti-corruption layers)?
- Are service contracts versioned and backwards-compatible?
- Is the system resilient to partial failures (circuit breakers, retries with backoff, timeouts)?
- For each outbound call: what happens when it is down or slow, is a retry safe to repeat, and what gets logged? Say what the caller does while the dependency is down.
Scalability and operability
- Where are the bottlenecks if load increases 10×? 100×?
- Are stateful components identifiable and independently scalable?
- Is observability (logging, tracing, metrics) a first-class concern in the design?
- What does the design add to daily operations? Name the new queues, dashboards and runbooks someone must watch or run.
Security architecture
- Are trust boundaries explicit?
- Does the design apply least-privilege (services only access what they need)?
- Are secrets injected at runtime, never baked in?
Advanced patterns guide
Use this section when a team is considering event sourcing, CQRS, or horizontal scaling patterns. These patterns carry significant complexity cost — consult this section to confirm fit before recommending them.
Event sourcing
What it is: Store the history of state changes as an immutable log of domain events, rather than the current state. Current state is derived by replaying events.
When it fits:
- Audit trail is a first-class product requirement (financial ledgers, compliance workflows, health records)
- The product needs temporal queries ("what was the state at time T?")
- Business events are intrinsically meaningful and must be observable by multiple consumers independently
- The team is willing to invest in read model projection infrastructure
When it does not fit:
- Simple CRUD apps with no audit or temporal query requirements
- Small teams without experience operating event stores
- When the "history" requirement can be met by a simple
updated_at timestamp and an audit log table
- When querying current state is the dominant access pattern and projections would add latency without benefit
Anti-patterns to watch:
- Using event sourcing as the persistence layer for every entity regardless of whether events are meaningful
- Treating every field change as a domain event (creates noise; events should represent business facts, not technical mutations)
- Failing to version events — event schema evolution in a durable log is significantly harder than schema migration
- Not defining explicit projection rebuild strategies before going to production
CQRS (Command Query Responsibility Segregation)
What it is: Separate the write model (commands, business rules) from the read model (queries, views optimized for consumption). Write and read sides can use different stores.
When it fits:
- Read and write throughput requirements are significantly different and one side is a bottleneck
- Query shape is fundamentally different from write shape (complex joins vs simple entity writes)
- The read side can tolerate eventual consistency (async projection updates)
- Event sourcing is in use (CQRS is a natural complement, not a requirement)
When it does not fit:
- Simple domains where a single database model serves reads and writes adequately
- When strong consistency is required everywhere — CQRS typically introduces eventual consistency on the read side
- When the team cannot afford to maintain two models (write and read) independently
- As a solution to a performance problem that a database index or query optimization would solve
Anti-patterns to watch:
- Applying CQRS to every aggregate regardless of whether the read/write impedance mismatch exists
- Building a CQRS system without a clear projection update strategy (how stale is "too stale"?)
- Using CQRS to avoid writing good queries rather than because the domain genuinely needs it
Horizontal scaling patterns
Sharding
- Partition data across nodes by a shard key so each node owns a subset of the dataset.
- Shard key choice is critical and nearly irreversible: choose a key with high cardinality and even distribution.
- Hot shards (one shard receiving disproportionate traffic) eliminate the benefit — validate shard key distribution before committing.
- Cross-shard queries and transactions become expensive or impossible — design to avoid them.
- When to use: dataset is too large for a single node; write throughput exceeds single-node capacity.
Partitioning
- Partition a table by a range or hash of a column (e.g. date range, tenant ID) within a single logical database.
- Less operationally complex than sharding — supported natively by most major databases.
- Improves query performance when the partition key matches the most common query filter.
- When to use: very large tables where queries are naturally scoped to a partition; time-series data; archival patterns.
Federation (functional sharding)
- Split different domains or features into separate databases (not tables), each owned by a specific service.
- Reduces cross-domain coupling; each service scales independently.
- Eliminates cross-domain JOINs — enforce domain boundaries at the application layer.
- When to use: microservices architecture with well-defined bounded contexts; when one domain's I/O is throttling another's performance.
Decision guide:
| Scale problem |
Preferred pattern |
| Single large table with time-based queries |
Table partitioning |
| Multi-tenant data at high volume per tenant |
Sharding by tenant ID |
| Cross-service data coupling and scaling bottleneck |
Federation |
| Distributed write load across homogeneous data |
Sharding |
Workflow
Read the current architecture — Resolve the project root and analysis scope; identify structure from code, not docs. Map modules, layers, entry points, key data flows, and external dependencies with source locations. Distinguish a pinned revision from working-tree edits and state unread areas. Record the runtime and framework versions the code runs, from its manifests and lockfiles. A design that needs a newer version is an upgrade decision. Start from the current infra map (where each process runs, how many instances run at once, where state and sessions live), not from an assumed one.
Choose a view that answers the question — Use C4 Level 2 (Container) or Level 3 (Component) for boundaries; sequence for call order, dataflow for movement/ownership, workflow for process, and lifecycle for state transitions. A concise text map or Mermaid is the portable default; no diagram runtime is required. Name responsibilities and support relationships with call, registration, transport, or configuration evidence. Preserve direction, action/protocol, synchronous/asynchronous behavior, and failure paths where verified. Do not infer runtime causality from names or file proximity.
Apply the architectural lenses above — Work through each relevant lens and note concerns. Then walk the what-ifs: empty, duplicate, concurrent, retried, out of order, partial failure, and a dependency that is down.
Distinguish local fix from structural need — Can this be solved with a small change inside the current boundary? Or does it require moving the boundary? Apply the principle: prefer local fixes unless the structure materially blocks correctness, maintainability, or delivery.
Write an Architecture Decision Record (ADR) when recommending a structural direction:
- Context: what is the problem and why does the current structure not serve it?
- Decision: what change is recommended?
- Consequences: what gets better, what gets harder, what risks remain?
- Alternatives considered: what other options were evaluated and why rejected?
Write an ADR only when all three hold: the decision is hard to reverse, a future reader would find it surprising without context, and it was a real trade-off between genuine alternatives. If one is missing, skip the ADR.
When the model itself is changing, sharpen the domain language as you go: call out a term that conflicts with the project glossary, propose one canonical name for an overloaded term (for example Customer versus User), stress-test relationships with concrete edge-case scenarios, and check whether the code agrees with what was just said. Keep the glossary free of implementation detail, and update it when a term is resolved rather than in a batch later.
Surface the residual risks — Every architecture has tradeoffs. Name them explicitly so the user can make an informed decision. Include the deploy path. In a rolling deploy, old and new code run side by side, so change things additively first and contract later. Name how existing data moves: expand, chunked backfill, cutover, and the way back.
Guardrails
- Do not recommend microservices for a team of two. Match architecture complexity to team size and scale requirements.
- Do not propose a rewrite when a smaller boundary adjustment solves the problem.
- Do not conflate "best in theory" with "best for this team now."
- If recommending event sourcing, CQRS, or a distributed pattern, require a concrete reason why a simpler approach fails.
- Keep source inspection, automated checks, observed runtime behavior, and visual review separate. A diagram rendering or a valid file/line reference does not prove architectural correctness. Re-check source evidence after a change before reusing a map.
Output format
Architecture summary: [current structure in plain language]
Structural concerns (by lens):
Layering: [findings]
Boundaries: [findings]
Data ownership: [findings]
Integrations: [findings]
Scalability: [findings]
ADR (only when the step 5 gate holds; otherwise omit):
Context: [problem]
Decision: [recommended direction]
Consequences: [better / harder / risks]
Alternatives: [what was rejected and why]
Local fix vs structural change: [verdict + reasoning]
Residual risks: [what remains after the recommendation]
References
../../references/playbooks/architecture-playbook.md
../../references/checklists/architecture-review-checklist.md
../../references/checklists/engineering-quality-bar.md
ADR gate and glossary practice adapted in part from engineering/domain-modeling (skills pack by Matt Pocock, MIT).
Backend API checks
When the design includes an HTTP backend, check these before recommending a shape:
- Resource-based URLs with filtering, sorting and pagination as query parameters; auth, logging and rate limiting as middleware, not repeated in handlers.
- Controllers stay thin: validation and the response shape at the edge, business rules in a service, data access behind a repository only when it earns its keep (a second store, heavy test seams). Do not add a repository layer over an ORM by reflex.
- Reads: select only needed columns, batch-fetch related rows instead of querying per row (N+1), and wrap multi-write operations in one transaction.
- Caching: cache-aside with a TTL, with the invalidation path named for every write that changes the cached value. Say how stale is acceptable.
- Errors: one central handler maps known operational errors to status codes, validation failures to 400 with details, and everything else to a generic 500 that logs the cause but does not leak it.
- Retries: exponential backoff with a cap, only for idempotent calls or calls with an idempotency key.
- Rate limits belong in a shared store, gateway or platform limiter, never per-process counters (they reset on deploy and split across replicas).
- Background work: an in-process array queue loses jobs on restart. Use a durable queue, make jobs idempotent, and record failures instead of only logging them.
- Structured JSON logs with a request id, and no secrets or tokens in them.
Adapted in part from ECC skills/backend-patterns (affaan-m/ECC, MIT).
1---2name: bosskuai-software-architecture3description: Use when deciding software architecture, module boundaries, system design, integration design, layering decisions, structural refactors, and long-term maintainability tradeoffs.4metadata:5 source: https://skillmd.com/skills/wankimmy/bosskuai-software-architecture6---78# BosskuAI Software Architecture910Use this skill when the main question is **structural** — where does this belong, how should components relate, and what are the long-term consequences of this design?1112## How this differs from nearby skills1314- **`bosskuai-code-revamp`**: executes a structural change once the direction is decided; this skill decides what the direction should be.15- **`bosskuai-codebase-analysis`**: orients you in an unfamiliar codebase; load first if the current structure is unclear before making architectural recommendations.16- **`bosskuai-engineering-delivery`**: implements the chosen architecture; this skill decides what to build.17- **`bosskuai-rigorous-code-review`**: reviews a specific diff; this skill reviews the structural design that diff embodies.1819## Mindset2021- The best architecture decision is usually the smallest commitment that preserves future optionality.22- Coupling is the enemy — hidden coupling is the worst kind.23- Read the code before making structure claims. Docs are aspirational; code is actual.24- Non-functional requirements (scalability, availability, consistency, latency) constrain structure more than feature requirements do.2526## Architectural lenses to apply2728Apply whichever are relevant; skip clearly irrelevant ones:2930**Layering and responsibility**31- Is logic in the right layer (presentation, application, domain, infrastructure)?32- Is there leakage across layer boundaries (UI calling DB directly, domain importing HTTP)?33- Is the domain model anemic (no behavior) or over-entangled (too many dependencies)?3435**Module and service boundaries**36- Does each module have a single clear owner and a stable public contract?37- Are bounded contexts explicit (DDD) or implicit and blurry?38- Where is the coupling highest? Is it necessary or accidental?3940**Data ownership and consistency**41- Who owns each piece of data? Can two services write to the same record?42- Is eventual consistency acceptable, or is strong consistency required?43- Are CQRS or event sourcing patterns appropriate, or over-engineering for the current scale?44- For each shared write, which guard holds it: a transaction, a row lock, a unique constraint or an idempotency key? A write with no guard is a race.4546**Integration and external dependencies**47- Are external integrations behind abstraction boundaries (anti-corruption layers)?48- Are service contracts versioned and backwards-compatible?49- Is the system resilient to partial failures (circuit breakers, retries with backoff, timeouts)?50- For each outbound call: what happens when it is down or slow, is a retry safe to repeat, and what gets logged? Say what the caller does while the dependency is down.5152**Scalability and operability**53- Where are the bottlenecks if load increases 10×? 100×?54- Are stateful components identifiable and independently scalable?55- Is observability (logging, tracing, metrics) a first-class concern in the design?56- What does the design add to daily operations? Name the new queues, dashboards and runbooks someone must watch or run.5758**Security architecture**59- Are trust boundaries explicit?60- Does the design apply least-privilege (services only access what they need)?61- Are secrets injected at runtime, never baked in?6263## Advanced patterns guide6465Use this section when a team is considering event sourcing, CQRS, or horizontal scaling patterns. These patterns carry significant complexity cost — consult this section to confirm fit before recommending them.6667### Event sourcing6869**What it is:** Store the history of state changes as an immutable log of domain events, rather than the current state. Current state is derived by replaying events.7071**When it fits:**72- Audit trail is a first-class product requirement (financial ledgers, compliance workflows, health records)73- The product needs temporal queries ("what was the state at time T?")74- Business events are intrinsically meaningful and must be observable by multiple consumers independently75- The team is willing to invest in read model projection infrastructure7677**When it does not fit:**78- Simple CRUD apps with no audit or temporal query requirements79- Small teams without experience operating event stores80- When the "history" requirement can be met by a simple `updated_at` timestamp and an audit log table81- When querying current state is the dominant access pattern and projections would add latency without benefit8283**Anti-patterns to watch:**84- Using event sourcing as the persistence layer for every entity regardless of whether events are meaningful85- Treating every field change as a domain event (creates noise; events should represent business facts, not technical mutations)86- Failing to version events — event schema evolution in a durable log is significantly harder than schema migration87- Not defining explicit projection rebuild strategies before going to production8889### CQRS (Command Query Responsibility Segregation)9091**What it is:** Separate the write model (commands, business rules) from the read model (queries, views optimized for consumption). Write and read sides can use different stores.9293**When it fits:**94- Read and write throughput requirements are significantly different and one side is a bottleneck95- Query shape is fundamentally different from write shape (complex joins vs simple entity writes)96- The read side can tolerate eventual consistency (async projection updates)97- Event sourcing is in use (CQRS is a natural complement, not a requirement)9899**When it does not fit:**100- Simple domains where a single database model serves reads and writes adequately101- When strong consistency is required everywhere — CQRS typically introduces eventual consistency on the read side102- When the team cannot afford to maintain two models (write and read) independently103- As a solution to a performance problem that a database index or query optimization would solve104105**Anti-patterns to watch:**106- Applying CQRS to every aggregate regardless of whether the read/write impedance mismatch exists107- Building a CQRS system without a clear projection update strategy (how stale is "too stale"?)108- Using CQRS to avoid writing good queries rather than because the domain genuinely needs it109110### Horizontal scaling patterns111112**Sharding**113- Partition data across nodes by a shard key so each node owns a subset of the dataset.114- Shard key choice is critical and nearly irreversible: choose a key with high cardinality and even distribution.115- Hot shards (one shard receiving disproportionate traffic) eliminate the benefit — validate shard key distribution before committing.116- Cross-shard queries and transactions become expensive or impossible — design to avoid them.117- When to use: dataset is too large for a single node; write throughput exceeds single-node capacity.118119**Partitioning**120- Partition a table by a range or hash of a column (e.g. date range, tenant ID) within a single logical database.121- Less operationally complex than sharding — supported natively by most major databases.122- Improves query performance when the partition key matches the most common query filter.123- When to use: very large tables where queries are naturally scoped to a partition; time-series data; archival patterns.124125**Federation (functional sharding)**126- Split different domains or features into separate databases (not tables), each owned by a specific service.127- Reduces cross-domain coupling; each service scales independently.128- Eliminates cross-domain JOINs — enforce domain boundaries at the application layer.129- When to use: microservices architecture with well-defined bounded contexts; when one domain's I/O is throttling another's performance.130131**Decision guide:**132133| Scale problem | Preferred pattern |134|--------------|------------------|135| Single large table with time-based queries | Table partitioning |136| Multi-tenant data at high volume per tenant | Sharding by tenant ID |137| Cross-service data coupling and scaling bottleneck | Federation |138| Distributed write load across homogeneous data | Sharding |139140## Workflow1411421. **Read the current architecture** — Resolve the project root and analysis scope; identify structure from code, not docs. Map modules, layers, entry points, key data flows, and external dependencies with source locations. Distinguish a pinned revision from working-tree edits and state unread areas. Record the runtime and framework versions the code runs, from its manifests and lockfiles. A design that needs a newer version is an upgrade decision. Start from the current infra map (where each process runs, how many instances run at once, where state and sessions live), not from an assumed one.1431442. **Choose a view that answers the question** — Use C4 Level 2 (Container) or Level 3 (Component) for boundaries; sequence for call order, dataflow for movement/ownership, workflow for process, and lifecycle for state transitions. A concise text map or Mermaid is the portable default; no diagram runtime is required. Name responsibilities and support relationships with call, registration, transport, or configuration evidence. Preserve direction, action/protocol, synchronous/asynchronous behavior, and failure paths where verified. Do not infer runtime causality from names or file proximity.1451463. **Apply the architectural lenses** above — Work through each relevant lens and note concerns. Then walk the what-ifs: empty, duplicate, concurrent, retried, out of order, partial failure, and a dependency that is down.1471484. **Distinguish local fix from structural need** — Can this be solved with a small change inside the current boundary? Or does it require moving the boundary? Apply the principle: prefer local fixes unless the structure materially blocks correctness, maintainability, or delivery.1491505. **Write an Architecture Decision Record (ADR)** when recommending a structural direction:151 - **Context**: what is the problem and why does the current structure not serve it?152 - **Decision**: what change is recommended?153 - **Consequences**: what gets better, what gets harder, what risks remain?154 - **Alternatives considered**: what other options were evaluated and why rejected?155156 Write an ADR only when all three hold: the decision is hard to reverse, a future reader would find it surprising without context, and it was a real trade-off between genuine alternatives. If one is missing, skip the ADR.157158 When the model itself is changing, sharpen the domain language as you go: call out a term that conflicts with the project glossary, propose one canonical name for an overloaded term (for example Customer versus User), stress-test relationships with concrete edge-case scenarios, and check whether the code agrees with what was just said. Keep the glossary free of implementation detail, and update it when a term is resolved rather than in a batch later.1591606. **Surface the residual risks** — Every architecture has tradeoffs. Name them explicitly so the user can make an informed decision. Include the deploy path. In a rolling deploy, old and new code run side by side, so change things additively first and contract later. Name how existing data moves: expand, chunked backfill, cutover, and the way back.161162## Guardrails163164- Do not recommend microservices for a team of two. Match architecture complexity to team size and scale requirements.165- Do not propose a rewrite when a smaller boundary adjustment solves the problem.166- Do not conflate "best in theory" with "best for this team now."167- If recommending event sourcing, CQRS, or a distributed pattern, require a concrete reason why a simpler approach fails.168- Keep source inspection, automated checks, observed runtime behavior, and visual review separate. A diagram rendering or a valid file/line reference does not prove architectural correctness. Re-check source evidence after a change before reusing a map.169170## Output format171172```173Architecture summary: [current structure in plain language]174Structural concerns (by lens):175 Layering: [findings]176 Boundaries: [findings]177 Data ownership: [findings]178 Integrations: [findings]179 Scalability: [findings]180ADR (only when the step 5 gate holds; otherwise omit):181 Context: [problem]182 Decision: [recommended direction]183 Consequences: [better / harder / risks]184 Alternatives: [what was rejected and why]185Local fix vs structural change: [verdict + reasoning]186Residual risks: [what remains after the recommendation]187```188189## References190191- `../../references/playbooks/architecture-playbook.md`192- `../../references/checklists/architecture-review-checklist.md`193- `../../references/checklists/engineering-quality-bar.md`194195ADR gate and glossary practice adapted in part from engineering/domain-modeling (skills pack by Matt Pocock, MIT).196197## Backend API checks198199When the design includes an HTTP backend, check these before recommending a shape:200201- Resource-based URLs with filtering, sorting and pagination as query parameters; auth, logging and rate limiting as middleware, not repeated in handlers.202- Controllers stay thin: validation and the response shape at the edge, business rules in a service, data access behind a repository only when it earns its keep (a second store, heavy test seams). Do not add a repository layer over an ORM by reflex.203- Reads: select only needed columns, batch-fetch related rows instead of querying per row (N+1), and wrap multi-write operations in one transaction.204- Caching: cache-aside with a TTL, with the invalidation path named for every write that changes the cached value. Say how stale is acceptable.205- Errors: one central handler maps known operational errors to status codes, validation failures to 400 with details, and everything else to a generic 500 that logs the cause but does not leak it.206- Retries: exponential backoff with a cap, only for idempotent calls or calls with an idempotency key.207- Rate limits belong in a shared store, gateway or platform limiter, never per-process counters (they reset on deploy and split across replicas).208- Background work: an in-process array queue loses jobs on restart. Use a durable queue, make jobs idempotent, and record failures instead of only logging them.209- Structured JSON logs with a request id, and no secrets or tokens in them.210211Adapted in part from ECC skills/backend-patterns (affaan-m/ECC, MIT).