#211API Boundary Matrix6 cells12 rules6 anti8 hints
Determines where API boundaries are drawn β what is exposed, what is internal, how requests/responses are shaped, and how versioning works across boundaries.
boundary_typeexposure_levelcontract_formatversioning
api_001
When exposing a public REST API, version endpoints explicitly and define contracts via OpenAPI.
β
RULES (2)
Use path-based versioning (e.g. /v1/resource)
Publish OpenAPI spec for consumers
β ANTI-PATTERNS (1)
Changing request/response shape without version bump
π» CODE HINTS (2)
GET /v1/products
openapi: 3.0.0
api_002
For service-to-service internal APIs, use strongly-typed contracts (e.g. protobuf) and evolve schemas with backward compatibility.
β
RULES (2)
Use gRPC or protobuf schemas
Avoid removing fields or changing types
β ANTI-PATTERNS (1)
Relying on untyped JSON between services
π» CODE HINTS (1)
message Order { string id = 1; repeated Item items = 2; }
api_003
When using a Backend-for-Frontend (BFF) pattern, shape DTOs per frontend view to minimize over-fetching and logic duplication.
β
RULES (2)
Assemble DTOs from multiple internal services
Expose only what UI needs
β ANTI-PATTERNS (1)
Returning raw backend entities with extra irrelevant fields
π» CODE HINTS (1)
return { title: product.name, price: product.displayPrice }
api_004
Define a clear mapping layer between transport DTOs and internal models to decouple domain from API shape.
β
RULES (2)
Map API DTOs to domain objects via mapper classes
Avoid leaking internal naming or structure
β ANTI-PATTERNS (1)
Using internal domain object as API response directly
π» CODE HINTS (1)
ProductDto.from(product)
api_005
Use an API Gateway to enforce routing, rate limiting, auth and path rewriting based on routing policy.
β
RULES (2)
Define path rules in gateway config
Enforce authentication at gateway layer
β ANTI-PATTERNS (1)
Embedding routing logic into individual microservices
π» CODE HINTS (1)
route /v1 β service-a
api_006
For GraphQL APIs, expose a single endpoint that supports flexible queries while enforcing schema contract.
β
RULES (2)
Use schema-first design
Enforce resolvers per type with access control
β ANTI-PATTERNS (1)
Over-fetching due to uncontrolled nested queries
π» CODE HINTS (2)
POST /graphql
type Product { name: String price: Float }
π§ͺ VALIDATION
Verify: all public APIs are versioned and documented, internal APIs use typed contracts, BFF responses match UI needs, mapping layer exists between DTOs and domain models, API gateway routes and protects correctly, GraphQL endpoint supports introspection and validation.
#212Request Lifecycle Matrix6 cells12 rules6 anti8 hints
Determines the lifecycle of an API request β from initiation through loading states, response handling, error recovery, and retry to final state.
lifecycle_phasestate_trackingerror_handlingcancellation
reqlife_001
When initiating an API request, set a loading state immediately to reflect progress to the UI.
β
RULES (2)
Set isLoading=true before sending request
Disable UI elements (e.g. buttons) to prevent resubmission
β ANTI-PATTERNS (1)
UI appears idle while request is in progress
π» CODE HINTS (2)
setState({ isLoading: true });
button.disabled = true
reqlife_002
When the response is successful, update the UI with the result and clear the loading state.
β
RULES (2)
Write data to view model or state
Set isLoading=false after success
β ANTI-PATTERNS (1)
Leaving stale data visible after successful response
π» CODE HINTS (1)
setState({ data: response.data, isLoading: false });
reqlife_003
When a request fails, store the error message and allow user retry.
β
RULES (2)
Set error state with message
Display retry button or option
β ANTI-PATTERNS (1)
Swallowing errors silently or showing generic alert only
π» CODE HINTS (2)
setState({ error: err.message })
<button onClick={retry}>Retry</button>
reqlife_004
When the user cancels an in-flight request, use AbortController to terminate fetch early.
β
RULES (2)
Create controller before fetch
Call controller.abort() on cancel
β ANTI-PATTERNS (1)
Letting in-flight request complete even after user navigated away
π» CODE HINTS (1)
const controller = new AbortController(); fetch(url, { signal: controller.signal }); controller.abort();
reqlife_005
When same request is triggered multiple times quickly, prevent duplicates by checking or caching in-flight state.
β
RULES (2)
Track requests in a Set or Map
Do not send request if already pending
β ANTI-PATTERNS (1)
Allowing multiple identical requests in parallel
π» CODE HINTS (1)
if (pendingRequests.has(url)) return;
reqlife_006
When a request exceeds expected duration, fail gracefully with fallback or retry.
β
RULES (2)
Set timeout manually if not built-in
Provide cached data or user feedback
β ANTI-PATTERNS (1)
Hanging UI with no error or fallback after 30s
π» CODE HINTS (1)
setTimeout(() => controller.abort(), 5000);
π§ͺ VALIDATION
Verify: loading state toggles correctly, data/state updated after response, error/retry path shown to user, cancellation via AbortController works, duplicate requests blocked, timeouts handled with fallback.
#213Matrix 213 β Response Handling Matrix6 cells18 rules18 anti6 hints
Define how to structure, classify, and act on responses from APIs, services, or other I/O systems to ensure safe and predictable handling across layers.
response_classificationparsing_strategysuccess_condition_definitionside_effect_triggeringtimeout_and_retry_policyresponse_logging_scope
SUCCESS_PAYLOAD_EXTRACTION
When receiving a successful API response with nested data
β
RULES (3)
Check HTTP status code or equivalent success indicator
Parse only validated fields from payload
Trigger state update after transformation
β ANTI-PATTERNS (3)
Blindly trusting response structure
Skipping null/undefined checks
Updating UI before payload is validated
π» CODE HINTS (1)
if (res.status === 200) setData(res.data.items)
EMPTY_RESPONSE_HANDLING
When external service returns no data or empty body
β
RULES (3)
Define default fallback structure
Warn user if contextually abnormal
Skip downstream logic if blocking
β ANTI-PATTERNS (3)
Rendering blank UI without message
Throwing error on legitimate empty result
Passing undefined to logic expecting arrays
π» CODE HINTS (1)
if (!data || data.length === 0) showEmptyState()
RETRYABLE_TRANSIENT_FAILURES
When receiving 5xx, network errors, or timeouts
β
RULES (3)
Detect transient failure categories
Apply exponential backoff for retries
Abort retries after fixed attempts
β ANTI-PATTERNS (3)
Retrying indefinitely
Failing silently
Retrying client-side 4xx responses
π» CODE HINTS (1)
retryWithBackoff(fn, { maxAttempts: 3 })
MULTI_RESPONSE_AGGREGATION
When coordinating results from multiple API calls
β
RULES (3)
Wait for all or fallback with partial mode
Normalize structures into common model
Tag partial/incomplete results if needed
β ANTI-PATTERNS (3)
Failing entire flow if one call fails
Merging incompatible payloads
Assuming response order guarantees
π» CODE HINTS (1)
Promise.allSettled(requests).then(joinResponses)
ASYNC_RESPONSE_DECODING_STRATEGY
When payloads are streamed or encoded
β
RULES (3)
Use streaming parsers or incremental decoding
Run parsing in worker thread if large
Log decoding errors with position/context
β ANTI-PATTERNS (3)
Decoding synchronously on main thread
Assuming fixed encoding format
Ignoring partial decode failures
π» CODE HINTS (1)
reader.read().then(decodeChunk)
RESPONSE_LOGGING_AND_METRICS
When monitoring system health and performance
β
RULES (3)
Log status code and endpoint per request
Tag anomalies or slow responses
Forward metrics to observability platform
β ANTI-PATTERNS (3)
Logging full payloads in prod
Not sampling high-frequency endpoints
No alerting for abnormal patterns
π» CODE HINTS (1)
logResponse({ path, status, latency })
π§ͺ VALIDATION
Simulate various response patterns: success, empty, retryable, partial. Confirm extraction, aggregation, and retry logic behave as defined. Monitor logs and metrics for classification accuracy.
#214HTTP Method Semantics Matrix6 cells12 rules6 anti7 hints
Determines correct usage of HTTP methods β GET for reads, POST for creation, PUT/PATCH for updates, DELETE for removal β ensuring idempotency and cacheability per method.
http_methodidempotencycacheabilitypayload_semantics
http_001
When retrieving data without side-effects, use GET which is safe, idempotent, and cacheable.
β
RULES (2)
Use GET for read-only operations
Support browser and CDN caching with proper headers
β ANTI-PATTERNS (1)
Modifying server state via GET request
π» CODE HINTS (1)
GET /users/42 β 200 OK
http_002
When creating new resources or triggering side effects, use POST β it's not idempotent and typically non-cacheable.
β
RULES (2)
Use POST to create or trigger non-repeatable actions
Ensure server handles duplicate submissions if retried
β ANTI-PATTERNS (1)
Using POST to update known resources (use PUT/PATCH instead)
π» CODE HINTS (1)
POST /users β { name: 'Alice' }
http_003
When fully replacing a known resource, use PUT β it's idempotent but generally not cached.
β
RULES (2)
PUT replaces entire resource at known URI
Repeat PUT with same payload yields same result
β ANTI-PATTERNS (1)
Using PUT for partial updates β prefer PATCH
π» CODE HINTS (1)
PUT /users/42 β { name: 'Updated' }
http_004
When partially updating resources, use PATCH β it can be idempotent if guarded with proper preconditions.
β
RULES (2)
Use PATCH with ETag or If-Match headers for safe partial updates
Define diff-based payload
β ANTI-PATTERNS (1)
Using PATCH without any precondition enforcement
π» CODE HINTS (1)
PATCH /users/42 β { name: 'Patched' } with If-Match
http_005
When removing resources, use DELETE β it is idempotent since repeated calls have the same effect.
β
RULES (2)
Ensure DELETE returns 204 or 200 even if resource is already deleted
DELETE should not error on second call
β ANTI-PATTERNS (1)
Failing DELETE on non-existent resource
π» CODE HINTS (1)
DELETE /users/42 β 204 No Content
http_006
When retrieving headers or checking capabilities without a body, use HEAD or OPTIONS β they are safe and side-effect free.
β
RULES (2)
HEAD returns headers only, no body
OPTIONS checks method support (CORS/preflight)
β ANTI-PATTERNS (1)
Sending large payloads with HEAD or OPTIONS
π» CODE HINTS (2)
HEAD /users/42
OPTIONS /users
π§ͺ VALIDATION
Verify: GET used for read-only with cache, POST for create with side effects, PUT for full replacement, PATCH for partial updates with conditions, DELETE is idempotent, HEAD/OPTIONS used for metadata or preflight.
#215Status Code Matrix6 cells12 rules6 anti6 hints
Determines correct HTTP status code usage β 2xx for success, 3xx for redirects, 4xx for client errors, 5xx for server errors β ensuring consistent API contracts.
status_rangesemanticsclient_actionretry_eligibility
status_001
When a request completes successfully and returns a response body, respond with 200 OK.
β
RULES (2)
Include entity in response body (e.g., JSON payload)
Set Content-Type correctly
β ANTI-PATTERNS (1)
Returning 200 with empty body for create or delete operations
π» CODE HINTS (1)
res.status(200).json(data)
status_002
When a new resource is created via POST, respond with 201 Created and include Location header.
β
RULES (2)
Set Location header to point to created resource URI
Optionally include resource in body
β ANTI-PATTERNS (1)
Returning 200 for POST creation without Location
π» CODE HINTS (1)
res.status(201).location('/resource/123').json(newResource)
status_003
When an operation succeeds but has no content to return, use 204 No Content.
β
RULES (2)
Ensure no response body is sent
Used for DELETE or PUT with no body
β ANTI-PATTERNS (1)
Sending JSON/null body with 204 status
π» CODE HINTS (1)
res.status(204).send()
status_004
When client sends invalid or missing input data, respond with 400 Bad Request.
β
RULES (2)
Return descriptive error message
Include validation details if available
β ANTI-PATTERNS (1)
Using 500 for input validation failures
π» CODE HINTS (1)
res.status(400).json({ error: 'Missing field: name' })
status_005
When a client requests a resource that doesnβt exist, return 404 Not Found.
β
RULES (2)
Do not leak internal details
Log internally if needed
β ANTI-PATTERNS (1)
Returning 200 with error in body for not-found cases
π» CODE HINTS (1)
res.status(404).json({ error: 'User not found' })
status_006
When an unexpected error occurs on the server, respond with 500 Internal Server Error.
β
RULES (2)
Return generic error message to client
Log full stack trace internally
β ANTI-PATTERNS (1)
Exposing exception stack trace to client
π» CODE HINTS (1)
res.status(500).json({ error: 'Internal server error' })
π§ͺ VALIDATION
Verify: 200 used for success with body, 201 for creation with Location, 204 with no body, 400 on input errors, 404 for missing, 500 for server failure.
#216Matrix 216 β Error Response Matrix6 cells18 rules18 anti6 hints
Define how to classify, propagate, and display error responses from APIs or IO systems, ensuring clarity, security, and recoverability across layers.
error_classificationuser_visibility_levelrecovery_capabilitysecurity_and_pii_exposurelogging_policyretry_guidance
CLIENT_SIDE_VALIDATION_ERRORS
When user input fails local validation before submission
β
RULES (3)
Highlight field inline
Explain issue in plain language
Prevent request dispatch
β ANTI-PATTERNS (3)
Showing generic error toast
Letting invalid input reach server
Using technical jargon for user errors
π» CODE HINTS (1)
setError('email', 'Must be valid format')
SERVER_BUSINESS_RULE_ERRORS
When server returns 400-series error for logic violations
β
RULES (3)
Parse error code and map to friendly text
Log server message for support
Allow user to correct and retry
β ANTI-PATTERNS (3)
Dumping raw server message to UI
Assuming all 400s are malformed input
Swallowing error without feedback
π» CODE HINTS (1)
if (err.code === 'OUT_OF_STOCK') showNotice('Item unavailable')
NETWORK_OR_TIMEOUT_ERRORS
When requests fail due to connectivity or delay
β
RULES (3)
Detect network failure or fetch timeout
Display retry button or auto-retry logic
Avoid blaming user for infra issues
β ANTI-PATTERNS (3)
Showing spinner forever
Hiding network errors silently
Triggering same request blindly again
π» CODE HINTS (1)
if (!navigator.onLine || timeout) showRetryModal()
FATAL_SERVER_ERRORS_500_RANGE
When backend returns internal error with no client fix
β
RULES (3)
Show generic apology message
Log incident with correlation ID
Route to failover path if available
β ANTI-PATTERNS (3)
Showing stacktrace to user
Looping retries on 500
Ignoring error for critical flows
π» CODE HINTS (1)
captureError(err, { context: 'checkout' })
SECURITY_RELATED_ERRORS
When authentication or authorization fails
β
RULES (3)
Avoid revealing protected resource existence
Redirect to login if token expired
Use vague but helpful language (e.g. 'Access denied')
β ANTI-PATTERNS (3)
Exposing role or permission detail
Throwing unhandled 401/403
Revealing endpoint logic via error text
π» CODE HINTS (1)
if (status === 403) redirect('/access-denied')
ERROR_LOGGING_AND_USER_FEEDBACK_LOOP
When error affects user experience and requires team visibility
β
RULES (3)
Send sanitized error to backend logger
Display toast or banner if helpful
Link to support if recurring
β ANTI-PATTERNS (3)
Logging full stack with PII
Telling user to 'try again later' without context
No capture of transient issues
π» CODE HINTS (1)
logClientError(e, { route, userId })
π§ͺ VALIDATION
Trigger each error type in isolation. Verify user message clarity, log content, retry behavior, and that sensitive data is not exposed in any layer.
#217Retry Strategy Matrix6 cells12 rules6 anti6 hints
Determines when and how failed requests are retried β exponential backoff, jitter, max attempts, and distinguishing transient from permanent failures.
failure_typebackoff_strategymax_attemptscircuit_integration
retry_001
When a transient error (e.g. timeout or HTTP 503) occurs, retry using exponential backoff to reduce pressure on remote system.
β
RULES (2)
Retry on 408, 429, 500, 502, 503, 504
Backoff with base delay 200ms doubling each attempt
β ANTI-PATTERNS (1)
Retrying instantly or on non-retryable codes like 400, 401
π» CODE HINTS (1)
delay = Math.min(3200, 200 * 2 ** attempt)
retry_002
When a permanent error occurs (e.g. HTTP 400, 404), fail fast without retries to avoid wasting compute.
β
RULES (2)
Do not retry on client errors unless 408 or 429
Surface failure immediately to caller
β ANTI-PATTERNS (1)
Retrying 400/404/401 repeatedly expecting recovery
π» CODE HINTS (1)
if (status in [400,404,401]) throw error
retry_003
When using backoff, add jitter to avoid retry synchronization across clients (thundering herd).
β
RULES (2)
Randomize delay within [0, backoff]
Use full jitter or decorrelated jitter variants
β ANTI-PATTERNS (1)
All clients retrying with identical schedule
π» CODE HINTS (1)
delay = Math.random() * base * 2 ** attempt
retry_004
When retrying, cap number of attempts to avoid infinite retry loops and resource exhaustion.
β
RULES (2)
Set retry cap (e.g. 3 or 5 attempts)
Abort and log after cap reached
β ANTI-PATTERNS (1)
Retry loops without exit condition
π» CODE HINTS (1)
if (attempts > 5) throw MaxRetriesExceeded
retry_005
When retrying non-GET operations (e.g. POST), include idempotency key to allow safe retries without side effects.
β
RULES (2)
Send Idempotency-Key header on first request
Server must store result or reject duplicate keys
β ANTI-PATTERNS (1)
Retrying POST without key β causes double insert
π» CODE HINTS (1)
headers['Idempotency-Key'] = uuidv4()
retry_006
When repeated retries fail, trigger circuit breaker to block further attempts and initiate fallback.
β
RULES (2)
Track retry failures in breaker state
Open circuit after threshold (e.g. 5 failures in 30s)
β ANTI-PATTERNS (1)
Ignoring retry failure stats β no circuit protection
π» CODE HINTS (1)
if (failures > 5) circuit.open()
π§ͺ VALIDATION
Verify: retries occur only for retryable failures, backoff includes jitter, retries capped, idempotency enforced, and circuit opens on repeated failure.
#218Timeout Strategy Matrix6 cells12 rules10 anti6 hints
Determines timeout policies for different request types β connect timeout, read timeout, overall deadline, and cascading timeout budgets.
timeout_typedurationfallbackpropagation
timeout_001
When initiating outbound connections, set a short connect timeout (e.g. 2β5s) to fail fast if remote is unreachable.
β
RULES (2)
Set connect timeout separately from read timeout
Fail connection attempts quickly to avoid hanging user experience
β ANTI-PATTERNS (2)
Using default system timeout (can be >30s)
Applying same timeout to both connect and read phases
π» CODE HINTS (1)
axios.create({ timeout: 5000, timeoutErrorMessage: 'Connect timeout' })
timeout_002
When waiting for response after successful connection, set read timeout (e.g. 10β30s) to abort stalled responses.
β
RULES (2)
Apply after TCP connection established
Abort read if time exceeds configured duration
β ANTI-PATTERNS (2)
Relying only on connect timeout (no read timeout)
Unlimited wait for backend response
π» CODE HINTS (1)
fetch(url, { signal: AbortSignal.timeout(15000) })
timeout_003
When designing service interactions, define end-to-end deadline budget across all hops (e.g. 1s for total roundtrip).
β
RULES (2)
Track elapsed time from entry point
Fail requests if overall deadline exceeded even if downstream accepts it
β ANTI-PATTERNS (1)
Each hop uses full timeout, causing additive delay
π» CODE HINTS (1)
if (elapsed > deadline) return HTTP 504
timeout_004
When forwarding requests to downstreams, subtract elapsed time and pass reduced timeout budget to next hop.
β
RULES (2)
Track total allowed time and decrement per service call
Inject timeout context into outbound headers
β ANTI-PATTERNS (1)
Restarting full timeout at each service boundary
π» CODE HINTS (1)
X-Timeout-Ms: deadline - elapsed
timeout_005
When timeout occurs, return cached or stale data instead of error to maintain degraded functionality.
β
RULES (2)
Use fallback only for non-critical freshness data
Clearly indicate response is stale in metadata
β ANTI-PATTERNS (2)
Serving stale data as fresh without indication
Using fallback when action must complete (e.g. payment)
π» CODE HINTS (1)
catch TimeoutError β return cache.get(key) + { stale: true }
timeout_006
When controlling timeout client-side, use AbortController to cancel fetch or async ops after configured time.
β
RULES (2)
Create controller and set timeout logic
Attach signal to fetch or async call
β ANTI-PATTERNS (2)
Not cleaning up abort controller
Multiple timers conflicting
π» CODE HINTS (1)
const ctrl = new AbortController(); setTimeout(() => ctrl.abort(), 10000); fetch(url, { signal: ctrl.signal })
π§ͺ VALIDATION
Verify: connect/read timeouts set correctly, deadline enforced across hops, cascading budget passed downstream, stale fallback used only when safe, AbortController cancels ops on time.
#219Matrix 219 β Rate Limiting Matrix6 cells18 rules18 anti6 hints
Define how to implement and enforce rate limiting on API calls β both for consumers and providers β covering quotas, throttling, bursts, feedback, and monitoring.
rate_limit_scopeenforcement_mechanismquota_tracking_methodburst_handling_policyconsumer_feedback_strategymonitoring_and_alerting
PER_USER_LIMIT_WITH_TOKEN_BUCKET
When protecting API per authenticated user
β
RULES (3)
Use token bucket with defined refill rate
Track tokens per user/session
Allow brief burst above steady rate
β ANTI-PATTERNS (3)
Flat limits for all users
No differentiation by plan
Dropping requests silently
π» CODE HINTS (1)
bucket.consume(userId) β 429 if empty
GLOBAL_LIMIT_WITH_LEAKY_BUCKET
When protecting backend from global overload
β
RULES (3)
Use leaky bucket with drain rate
Throttle excess with 503 or Retry-After
Apply circuit breaker at system edge
β ANTI-PATTERNS (3)
Letting bursts spike DB load
Over-committing upstream
Allowing queue growth unchecked
π» CODE HINTS (1)
if (!bucket.allow()) throw 503
API_KEY_QUOTA_TRACKING_AND RESET
When enforcing quotas per API client
β
RULES (3)
Track usage by API key
Reset quotas daily or monthly
Expose remaining quota in headers
β ANTI-PATTERNS (3)
Not resetting counters
No public feedback on usage
Same quota across tiers
π» CODE HINTS (1)
X-RateLimit-Remaining: 152
BURST_ALLOWANCE_WITH_JITTER
When allowing temporary spikes above baseline
β
RULES (3)
Allow small overages with decay
Add jitter to avoid synchronization
Use backoff after burst consumed
β ANTI-PATTERNS (3)
Fixed reset window
Immediate lockout after burst
Aligned bursts from all users
π» CODE HINTS (1)
burstWindow = base + random(0, 500ms)
CLIENT_FEEDBACK_ON_LIMIT_EXCEEDED
When clients exceed their quota
β
RULES (3)
Respond with 429 status
Include Retry-After or wait hints
Expose usage stats in dashboard or headers
β ANTI-PATTERNS (3)
Returning 500 on limit
No guidance on retry
No user-facing quota visibility
π» CODE HINTS (1)
HTTP 429 Retry-After: 120
REALTIME_ALERTING_ON_QUOTA_BREACH
When monitoring usage by tier or client
β
RULES (3)
Set thresholds for each plan or role
Alert on quota breach or anomaly
Log source IP, token, path
β ANTI-PATTERNS (3)
No alerts until system failure
No per-client observability
Letting trial users exhaust shared pool
π» CODE HINTS (1)
alert('rate_limit_exceeded', { apiKey, usage })
π§ͺ VALIDATION
Simulate burst traffic. Trigger per-user and global limit violations. Observe retry headers, backoff, alerting, and graceful degradation.
#220Matrix 220 β Pagination Matrix6 cells18 rules18 anti6 hints
Define how to choose and implement pagination strategies across APIs, UIs, and databases, balancing usability, performance, and scalability.
pagination_methodcursor_vs_offsetstate_persistence_strategybackend_capability_alignmentclient_navigation_behaviorscalability_limitations
OFFSET_BASED_PAGINATION_SIMPLE_LISTS
When retrieving static lists with low concurrency
β
RULES (3)
Use limit and offset parameters
Display total pages or item count
Avoid for large or dynamic datasets
β ANTI-PATTERNS (3)
Using offset when data mutates frequently
Paginating without bounding limit
Assuming total count is fast
π» CODE HINTS (1)
GET /items?limit=20&offset=40
CURSOR_BASED_PAGINATION_REALTIME_FEEDS
When paging through live or fast-changing data
β
RULES (3)
Use opaque cursor tokens
Return next/prev cursors in response
Enforce ordering guarantee on source
β ANTI-PATTERNS (3)
Encoding offset as cursor
Returning unordered results
Forgetting to invalidate old cursors
π» CODE HINTS (1)
GET /feed?cursor=abc123
INFINITE_SCROLL_UI_PATTERN
When user expects seamless scrolling without pagination UI
β
RULES (3)
Detect scroll threshold for fetch
Debounce load requests to avoid flood
Show loading indicator at bottom
β ANTI-PATTERNS (3)
Triggering fetch on every scroll event
No visual feedback of loading
Not handling end of list
π» CODE HINTS (1)
useIntersectionObserver(fetchMore)
PAGE_STATE_PERSISTENCE_ON_NAVIGATION
When navigating away and returning to a paginated view
β
RULES (3)
Store current page or cursor in route or memory
Restore scroll position on return
Avoid redundant refetching if cache valid
β ANTI-PATTERNS (3)
Always resetting to page 1
Hardcoding page state outside of routing
Invalidating cache on minor route changes
π» CODE HINTS (1)
router.push('/items?page=3')
HYBRID_BACKEND_PAGINATION_SUPPORT
When backend must support both cursor and offset clients
β
RULES (3)
Accept both offset and cursor query params
Detect mode and resolve appropriately
Document cursor constraints clearly
β ANTI-PATTERNS (3)
Allowing ambiguous pagination mode
Inconsistent page size behavior
Failing silently on bad cursor values
π» CODE HINTS (1)
if (cursor) { ... } else if (offset) { ... }
LIMIT_PAGINATION_DEPTH_FOR_SCALE
When paginating over very large datasets
β
RULES (3)
Set max offset or page depth limit
Encourage filtering or date scoping
Block deep paging with warning
β ANTI-PATTERNS (3)
Allowing offset=1,000,000
Returning massive page payloads
Exposing exact dataset size unnecessarily
π» CODE HINTS (1)
if (offset > 10000) return error('Too deep')
π§ͺ VALIDATION
Test paging behavior under offset and cursor modes. Simulate navigation, state restore, and edge scrolling. Confirm performance and API contract stability.
#221Matrix 221 β Filtering Matrix6 cells18 rules18 anti6 hints
Define how to design and apply filtering strategies on datasets across APIs, databases, and UI layers to ensure precision, performance, and consistency.
filter_expression_formatclient_vs_server_filteringfield_type_supportperformance_characteristicscomposability_and_nestinguser_customization_support
SERVER_SIDE_FILTERING_FOR_LARGE_SETS
When querying large datasets from backend
β
RULES (3)
Use parameterized query filters
Limit client-visible fields
Index commonly filtered fields
β ANTI-PATTERNS (3)
Sending full dataset to client for filtering
Hardcoding filter logic in app code
No control over filter complexity
π» CODE HINTS (1)
GET /products?category=books&price[lte]=20
CLIENT_SIDE_FILTERING_FOR_SMALL_SETS
When working with small cached lists in UI
β
RULES (3)
Perform filter in-memory on user input
Debounce filtering actions
Fallback to server when limit exceeded
β ANTI-PATTERNS (3)
Filtering on every keystroke without delay
Fetching entire dataset just to filter
Duplicating logic in multiple views
π» CODE HINTS (1)
const result = items.filter(x => x.name.includes(query))
ADVANCED_FILTER_BUILDER_SUPPORT
When allowing user to define multi-field, nested filters
β
RULES (3)
Support AND/OR nesting
Visualize filter logic as expression tree
Validate before applying
β ANTI-PATTERNS (3)
Storing filters as raw strings
Executing unparsed expressions
No UI feedback for malformed filters
π» CODE HINTS (1)
{ op: 'and', filters: [{ field: 'x', op: '>', val: 10 }, ...] }
TYPE_AWARE_FILTERING_SUPPORT
When filtering fields of varied data types
β
RULES (3)
Detect field type for operator selection
Support enums, dates, booleans appropriately
Validate filter format per type
β ANTI-PATTERNS (3)
Allowing text match on boolean field
Forgetting time zone logic in date filtering
Letting user choose invalid operator
π» CODE HINTS (1)
filter.field.type === 'date' β show date-picker + comparator
PERFORMANCE_BOUND_FILTER_STRATEGY
When filtering over potentially slow backend systems
β
RULES (3)
Impose field-level filter limits
Require indexed filters for remote queries
Warn user of expensive combinations
β ANTI-PATTERNS (3)
Allowing filter on unindexed text field
Combining many ORs without bound
Assuming backend always optimizes
π» CODE HINTS (1)
if (!field.indexed) return error('Field not searchable')
USER_PREFERENCES_AND_SAVED_FILTERS
When supporting saved views or custom filtering
β
RULES (3)
Serialize filters to shareable format
Store in user profile or local storage
Respect defaults + allow overrides
β ANTI-PATTERNS (3)
Losing filters on reload
Only saving UI state without logic
Storing opaque blob with no parse model
π» CODE HINTS (1)
localStorage.setItem('filters', JSON.stringify(currentFilters))
π§ͺ VALIDATION
Apply filters across datasets of various sizes and types. Validate client vs server logic split, type-specific operator behavior, and persistence of saved filters.
#222Matrix 222 β Sorting Matrix6 cells18 rules18 anti6 hints
Define how to apply sorting strategies to structured data across APIs, databases, and UIs while maintaining clarity, performance, and consistency.
sort_expression_formatdefault_sort_behaviormulti_field_sorting_supportfield_type_handlingperformance_considerationsuser_control_and_customization
DEFAULT_SORT_ON_PRIMARY_KEY
When no explicit sort is provided on a dataset
β
RULES (3)
Use primary key or created_at as fallback
Document default sort explicitly
Avoid random order returns
β ANTI-PATTERNS (3)
Leaving order undefined
Relying on database natural order
Inconsistent default sort across environments
π» CODE HINTS (1)
ORDER BY id ASC
MULTI_FIELD_SORTING_SUPPORT
When users want to sort by multiple columns
β
RULES (3)
Allow stable secondary sort fallback
Support client- or server-side expressions
Preserve tie-breaker logic
β ANTI-PATTERNS (3)
Overwriting previous sort on second field
Re-sorting full list client-side unnecessarily
Not aligning secondary sort with filter context
π» CODE HINTS (1)
ORDER BY status ASC, updated_at DESC
CLIENT_SIDE_SORT_FOR_SMALL_CACHES
When sorting small datasets already fetched in UI
β
RULES (3)
Use locale-aware string comparison
Respect numeric vs alpha types
Re-render only visible segment
β ANTI-PATTERNS (3)
Sorting blindly on stringified values
Triggering full UI reflow
Assuming sort works same across browsers
π» CODE HINTS (1)
items.sort((a,b) => a.name.localeCompare(b.name))
SERVER_SIDE_SORT_FOR_LARGE_LISTS
When working with large or paginated datasets
β
RULES (3)
Push sort expression to backend
Use indexed fields where possible
Align sort with pagination cursor field
β ANTI-PATTERNS (3)
Sorting large lists on frontend
Using unindexed sort keys
Changing sort order post-pagination
π» CODE HINTS (1)
GET /items?sort=price:desc
SORT_UI_CONTROL_PATTERNS
When exposing sorting to users in table or grid
β
RULES (3)
Support toggling asc/desc and reset
Show current sort indicators
Use accessible buttons and keyboard support
β ANTI-PATTERNS (3)
Hiding sort state from user
Toggling with every click without control
Non-interactive labels
π» CODE HINTS (1)
onClick: toggleSort(columnKey)
SORT_PERSISTENCE_AND_BOOKMARKING
When users navigate away and return to sorted views
β
RULES (3)
Store sort state in query string or route
Apply sort on re-render or mount
Allow shareable sorted URLs
β ANTI-PATTERNS (3)
Resetting sort on every view entry
Using internal-only state for sort
Breaking sort on reload
π» CODE HINTS (1)
router.push({ sort: 'name.asc' })
π§ͺ VALIDATION
Sort real datasets across types and sizes. Validate user controls, sort expression handling, default fallbacks, and sort order persistence across navigation and refresh.
#223Caching Strategy Matrix6 cells12 rules6 anti6 hints
Determines how data is cached across layers β browser cache, in-memory cache, API cache headers, and cache invalidation strategies.
cache_layerinvalidation_strategyttl_policyconsistency_model
cache_001
When using HTTP caching at the browser or CDN level, leverage ETag headers to validate freshness without full content download.
β
RULES (2)
Set ETag header based on resource hash
Respond with 304 Not Modified if ETag matches
β ANTI-PATTERNS (1)
Always returning 200 OK with full body even if unchanged
π» CODE HINTS (1)
res.setHeader('ETag', calculateHash(body))
cache_002
When enabling browser or CDN cache, use Cache-Control headers to define TTL and revalidation behavior.
β
RULES (2)
Use max-age=X for static assets
Use stale-while-revalidate to serve old while revalidating
β ANTI-PATTERNS (1)
Leaving cache behavior to default or missing Cache-Control
π» CODE HINTS (1)
Cache-Control: max-age=86400, stale-while-revalidate=3600
cache_003
When storing transient data in memory (e.g. Map or LRU), apply TTL-based eviction to avoid stale data and memory bloat.
β
RULES (2)
Store timestamp alongside value
Purge expired entries on access or interval
β ANTI-PATTERNS (1)
Keeping all items in memory indefinitely
π» CODE HINTS (1)
if (Date.now() - entry.ts > ttl) delete cache[key]
cache_004
When enabling offline support in PWAs, use service worker cache with an offline-first strategy to serve cached content before network fallback.
β
RULES (2)
Check CacheStorage before fetching
Fallback to network only if not in cache
β ANTI-PATTERNS (1)
Always attempting network fetch first in offline scenario
π» CODE HINTS (1)
event.respondWith(caches.match(req) || fetch(req))
cache_005
When a mutation (e.g. POST, PUT) occurs, invalidate relevant caches to maintain consistency.
β
RULES (2)
On write, delete affected keys in memory or IndexedDB
Clear stale cache entries on mutation acknowledgment
β ANTI-PATTERNS (1)
Leaving stale cache after data update
π» CODE HINTS (1)
onPostSuccess(() => cache.delete('/api/items'))
cache_006
When caching responses, include both URL and normalized query params in cache key to avoid mismatches.
β
RULES (2)
Sort and hash query parameters
Use `${url}::${hash(params)}` as key format
β ANTI-PATTERNS (1)
Using raw URL string without params handling
π» CODE HINTS (1)
const key = url + '::' + hash(JSON.stringify(sortedParams))
π§ͺ VALIDATION
Verify: ETag and Cache-Control headers used correctly, TTL works for memory caches, service worker serves offline reliably, mutations clear stale cache, and cache keys handle params correctly.
#224Matrix 224 β Cache Invalidation Matrix6 cells18 rules18 anti6 hints
Define strategies for invalidating cached data across layers and systems to ensure freshness, correctness, and performance balance.
cache_scopeinvalidation_triggerconsistency_guarantee_levelpropagation_timinguser_visibilitystaleness_tolerance
TIME_BASED_INVALIDATION_TTL
When cache can tolerate temporary staleness
β
RULES (3)
Define explicit TTL per resource
Expire entries asynchronously
Use background refresh if needed
β ANTI-PATTERNS (3)
Leaving items cached forever
No control over refresh interval
Over-reliance on default global TTL
π» CODE HINTS (1)
cache.set(key, value, { ttl: 600 })
MANUAL_INVALIDATION_ON_MUTATION
When data is changed by user or admin
β
RULES (3)
Trigger cache.clear(key) on mutation
Log invalidation reason
Invalidate affected related entries
β ANTI-PATTERNS (3)
Delaying invalidation until next read
Assuming update will auto-refresh
Only invalidating primary key but not related joins
π» CODE HINTS (1)
onUpdate: invalidate(['users', 'users:list'])
TAG_BASED_GROUP_INVALIDATION
When multiple cache entries belong to same domain
β
RULES (3)
Tag cache entries during write
Purge all tags on update or deploy
Use tag hierarchies if needed
β ANTI-PATTERNS (3)
Hardcoding related keys manually
Skipping tag cleanup
Allowing tag explosion without expiration
π» CODE HINTS (1)
cache.invalidateTags(['user'])
EVENT_DRIVEN_INVALIDATION
When updates happen across systems or users
β
RULES (3)
Emit invalidation events via pub/sub
Subscribe on cache layer or CDN edge
Include resource identity in message
β ANTI-PATTERNS (3)
Polling for changes unnecessarily
Allowing silent staleness
Lack of listener on subscriber side
π» CODE HINTS (1)
eventBus.publish('cache:invalidate', { resource: 'org:123' })
ON_NAVIGATION_REFETCH_POLICY
When user navigates back to a previously visited view
β
RULES (3)
Define cache revalidation policy on route
Clear or rehydrate cache after threshold
Use cache fingerprint or version tag
β ANTI-PATTERNS (3)
Blindly trusting navigation state
Reusing client cache without check
Missing cache key invalidation strategy
π» CODE HINTS (1)
useQuery({ staleTime: 0 })
USER_TRIGGERED_REFRESH_ACTIONS
When user explicitly wants to refresh stale or suspect data
β
RULES (3)
Expose refresh button on view
Bypass cache on user command
Show feedback that refresh is in progress
β ANTI-PATTERNS (3)
Forcing refresh without feedback
Hiding refresh controls in nested menus
Refreshing without cache bust mechanism
π» CODE HINTS (1)
onClick={() => queryClient.invalidateQueries('report')}
π§ͺ VALIDATION
Trigger each invalidation mode in isolation. Confirm refresh occurs, stale data does not persist, and logging captures timing and scope.
#225Streaming Matrix6 cells14 rules6 anti6 hints
Determines how streaming data is handled β SSE, WebSocket, chunked transfer, backpressure, and reconnection strategies.
stream_protocoldirectionbackpressurereconnection
stream_001
When pushing real-time updates from server to client, use Server-Sent Events (SSE) for efficient unidirectional streaming.
β
RULES (3)
Use 'text/event-stream' Content-Type
Reconnect onEventSource close or error
Keep connection alive with comment heartbeats
β ANTI-PATTERNS (1)
Using WebSocket for simple one-way updates unnecessarily
π» CODE HINTS (1)
const es = new EventSource('/events'); es.onmessage = fn
stream_002
When enabling real-time two-way communication, use WebSockets to allow both client and server to send messages anytime.
β
RULES (3)
Upgrade HTTP connection with 'Upgrade: websocket'
Maintain open socket for both directions
Handle ping/pong to detect disconnects
β ANTI-PATTERNS (1)
Using polling or SSE when full duplex required
π» CODE HINTS (1)
ws.send(JSON.stringify({ type: 'ping' }))
stream_003
When streaming data over HTTP without buffering full response, use chunked transfer encoding to flush data as it's available.
β
RULES (2)
Set Transfer-Encoding: chunked
Flush response manually after each write
β ANTI-PATTERNS (1)
Buffering entire payload before sending
π» CODE HINTS (1)
res.write('chunk'); res.flush()
stream_004
When consuming streamed response in browser, use ReadableStream API for progressive parsing and UI updates.
β
RULES (2)
Read from response.body.getReader() loop
Process text chunks as they arrive
β ANTI-PATTERNS (1)
Waiting for full body before parsing
π» CODE HINTS (1)
reader.read().then(({done,value}) => decode(value))
stream_005
When producer emits faster than consumer can process, apply backpressure via pause/resume or buffer windowing.
β
RULES (2)
Check consumer readiness before pushing
Queue or drop excess messages
β ANTI-PATTERNS (1)
Unbounded buffering causing memory pressure
π» CODE HINTS (1)
if (!canProcess) stream.pause()
stream_006
When connection drops, use exponential backoff to retry with increasing delay and avoid overload.
β
RULES (2)
Double retry delay after each failure (max cap)
Reset timer on success
β ANTI-PATTERNS (1)
Retrying immediately in a tight loop
π» CODE HINTS (1)
setTimeout(connect, Math.min(2 ** attempts * 1000, 30000))
π§ͺ VALIDATION
Verify: SSE used for push-only, WebSocket for full-duplex, chunked transfer avoids buffering, ReadableStream parsed progressively, backpressure avoids overflow, and reconnect uses backoff.
#226Matrix 226 β WebSocket Matrix6 cells18 rules18 anti6 hints
Define when and how to use WebSocket connections for real-time communication, ensuring scalability, reliability, and fallbacks.
connection_lifecyclemessage_routing_strategyauth_handling_methodfallback_and_reconnectscalability_architectureprotocol_standardization
BASIC_PUBSUB_CHANNEL_MODEL
When using WebSocket for simple topic-based updates
β
RULES (3)
Use named channels or topics
Support join/leave operations
Broadcast updates to subscribed clients only
β ANTI-PATTERNS (3)
Pushing all messages to all clients
Hardcoding topic names in frontend
Allowing anonymous wildcard subscriptions
π» CODE HINTS (1)
socket.emit('subscribe', 'news:weather')
CONNECTION_AUTHENTICATION_AND_REVOKE
When user identity is required for secure channels
β
RULES (3)
Authenticate on initial handshake
Refresh token before expiration
Disconnect or revoke on logout
β ANTI-PATTERNS (3)
Skipping auth in WebSocket layer
Letting expired tokens persist
Relying solely on cookie/session auth
π» CODE HINTS (1)
socket.emit('auth', { token })
RESILIENT_RECONNECT_WITH_BACKOFF
When connection may drop due to network issues
β
RULES (3)
Implement exponential backoff for reconnect
Cap retry count or interval
Inform user when offline for long
β ANTI-PATTERNS (3)
Reconnecting every 100ms indefinitely
Retrying without notifying user
Not distinguishing error types
π» CODE HINTS (1)
setTimeout(() => connect(), backoff[i++])
SERVER_SCALE_OUT_VIA_MESSAGE_BROKER
When many servers handle WebSocket clients
β
RULES (3)
Use Redis, NATS, or Kafka for cross-node pub/sub
Broadcast to other servers on internal publish
Avoid sticky session reliance if possible
β ANTI-PATTERNS (3)
Sending messages only to in-memory clients
Assuming single-node visibility
Not propagating disconnect events
π» CODE HINTS (1)
pubsub.publish('user:123', message)
PROTOCOL_VERSIONING_AND_ENVELOPE
When designing message format for WebSocket events
β
RULES (3)
Include type and version in each message
Wrap payload in a common envelope
Reject unsupported versions gracefully
β ANTI-PATTERNS (3)
Sending raw JSON without type metadata
Breaking changes without version bump
Omitting envelope structure
π» CODE HINTS (1)
{ type: 'chat.message', version: 1, payload: { ... } }
FALLBACK_TO_HTTP_POLLING_OR_SSE
When client or network blocks WebSocket use
β
RULES (3)
Detect WebSocket support at runtime
Fallback to HTTP polling or SSE
Unify message format across transports
β ANTI-PATTERNS (3)
Breaking app when WS not available
Using completely different format in fallback
No telemetry on fallback usage
π» CODE HINTS (1)
if (!supportsWebSocket()) useSSE()
π§ͺ VALIDATION
Test WebSocket and fallback modes under real network conditions. Confirm authentication, reconnect, and message routing work cross-node and survive version changes.
#227Matrix 227 β Realtime Sync Matrix6 cells18 rules18 anti6 hints
Define how to synchronize state in real-time across clients, tabs, or systems using push-based protocols or polling with consistency and efficiency.
sync_initiation_triggertransport_mechanismconflict_resolution_strategylatency_tolerancedata_granularitysubscription_scope
SERVER_PUSH_ON_MUTATION
When backend updates data relevant to connected clients
β
RULES (3)
Emit mutation event with diff
Only notify subscribed clients
Log push latency
β ANTI-PATTERNS (3)
Broadcasting full object on every change
Not filtering recipients
Letting outdated values overwrite local state
π» CODE HINTS (1)
emit('user:updated', { id, patch })
CLIENT_POLL_INTERVAL_FOR_STATIC_DATA
When data changes slowly or cannot use push
β
RULES (3)
Set polling interval based on volatility
Use ETag or last-modified headers
Avoid polling when tab is unfocused
β ANTI-PATTERNS (3)
Polling every few seconds on static data
Refetching entire dataset
Ignoring backoff or suppression rules
π» CODE HINTS (1)
setInterval(() => fetch('/feed'), 60000)
TAB_SYNC_WITH_BROADCAST_CHANNEL
When multiple tabs need to sync shared state
β
RULES (3)
Use BroadcastChannel or storage event
Send delta rather than full copy
Avoid infinite sync loops
β ANTI-PATTERNS (3)
Syncing whole state blindly
Missing source of truth determination
Triggering loops via localStorage writes
π» CODE HINTS (1)
channel.postMessage({ type: 'update', patch })
CONFLICT_RESOLUTION_VIA_TIMESTAMP
When same record may be updated from multiple sources
β
RULES (3)
Compare timestamps or version numbers
Accept latest update or flag conflict
Store metadata about update origin
β ANTI-PATTERNS (3)
Last-write-wins without explanation
Overwriting remote changes blindly
No tracking of update history
π» CODE HINTS (1)
if (incoming.updatedAt > local.updatedAt) accept()
FRAGMENTED_ENTITY_LEVEL_UPDATES
When synchronizing large or structured documents
β
RULES (3)
Use patch-based or operational transforms
Track per-section version or checksum
Render minimal UI diff
β ANTI-PATTERNS (3)
Re-rendering entire document
Dropping user input during merge
Syncing raw blobs without granularity
π» CODE HINTS (1)
patch({ section: 'body', changes: [...] })
REALTIME_SYNC_SUBSCRIPTION_SCOPE
When users watch entities or feeds in real time
β
RULES (3)
Subscribe only to visible or followed items
Auto-unsubscribe when navigating away
Expose sync state per entity
β ANTI-PATTERNS (3)
Staying subscribed to all entities always
No sync feedback for disconnected views
Holding memory for unused topics
π» CODE HINTS (1)
subscribe(entityId); onUnmount(() => unsubscribe(entityId))
π§ͺ VALIDATION
Simulate concurrent updates, tab interactions, and connection disruptions. Validate diff accuracy, conflict handling, and resource cleanup after unsubscription.
#228Matrix 228 β File Upload Matrix6 cells18 rules18 anti6 hints
Define how to architect and secure file uploads from client to server, ensuring scalability, validation, and user experience.
upload_methodfile_validation_strategystorage_destinationprogress_feedback_mechanismsecurity_controlsretry_and_resume_capability
DIRECT_UPLOAD_TO_CLOUD_STORAGE
When uploading large files directly from client
β
RULES (3)
Use pre-signed URLs or tokenized endpoints
Validate file metadata before signing
Secure expiration and access control
β ANTI-PATTERNS (3)
Allowing arbitrary files without limits
Hardcoding upload targets
Exposing credentials in client
π» CODE HINTS (1)
fetch('/sign-upload').then(res => uploadTo(res.url))
MULTIPART_FORM_UPLOAD_WITH_BACKEND_VALIDATION
When uploading small or structured files via form
β
RULES (3)
Use multipart/form-data encoding
Validate MIME type and schema server-side
Throttle request size and rate
β ANTI-PATTERNS (3)
Relying solely on frontend validation
Accepting file buffers blindly
Skipping MIME sniffing
π» CODE HINTS (1)
app.post('/upload', uploadMiddleware, validateFile, save)
CHUNKED_UPLOAD_FOR_LARGE_FILES
When uploading large files over unstable networks
β
RULES (3)
Split files into fixed-size chunks
Track upload status per chunk
Merge and verify on backend
β ANTI-PATTERNS (3)
Sending full file on retry
No way to resume after interruption
Merging chunks without hash check
π» CODE HINTS (1)
uploadChunk(chunk, index); finalizeUpload(fileId)
REALTIME_PROGRESS_FEEDBACK_UI
When users upload files through web UI
β
RULES (3)
Display percentage progress bar
Show estimated time remaining
Handle pause/cancel gracefully
β ANTI-PATTERNS (3)
No feedback until upload completes
Jumping progress or incorrect indicators
Blocking UI during upload
π» CODE HINTS (1)
xhr.upload.onprogress = (e) => updateBar(e.loaded / e.total)
SECURITY_AND_VIRUS_SCANNING
When accepting untrusted files from users
β
RULES (3)
Run antivirus or malware scan
Isolate uploads before processing
Reject based on denylist or scanning result
β ANTI-PATTERNS (3)
Processing file before scanning
Skipping scanning due to size
Failing open if scan errors
π» CODE HINTS (1)
clamd.scan(filePath).then(...)
RETRY_AND_RESUME_FAILED_UPLOADS
When network instability causes incomplete uploads
β
RULES (3)
Store partial upload state in client
Implement resume API with byte range
Provide retry UI on failure
β ANTI-PATTERNS (3)
Forcing full re-upload
Dropping uploads after timeout
Not informing user of partial progress
π» CODE HINTS (1)
headers: { 'Content-Range': 'bytes 1000-1999/4000' }
π§ͺ VALIDATION
Upload files of different sizes and types. Interrupt uploads to test resumability. Verify scanning, backend merging, progress updates, and security logs.
#229Matrix 229 β File Download Matrix6 cells18 rules18 anti6 hints
Define how to handle file downloads from web or service endpoints, balancing user experience, security, and compatibility.
download_initiation_methodauthentication_and_authorizationfile_streaming_strategyprogress_and_status_feedbackcontent_disposition_controlcross_browser_and_device_support
DIRECT_DOWNLOAD_VIA_LINK
When file is public and static
β
RULES (3)
Use anchor tag with href
Set download attribute for filename
Avoid JS if unnecessary
β ANTI-PATTERNS (3)
Triggering downloads with complex JS unnecessarily
Forgetting content-type headers
No fallback for mobile
π» CODE HINTS (1)
<a href='/files/manual.pdf' download>Download</a>
AUTHENTICATED_DOWNLOAD_ENDPOINT
When file access is restricted to logged-in users
β
RULES (3)
Send token or session cookie
Use server redirect to blob URL if needed
Return 403 on unauthorized attempts
β ANTI-PATTERNS (3)
Embedding auth token in href
Serving files without auth headers
Allowing open file URLs to be indexed
π» CODE HINTS (1)
GET /secure/file.pdf with Authorization: Bearer...
STREAMING_LARGE_FILES
When downloading large or unbuffered files
β
RULES (3)
Use HTTP range headers or content streaming
Pipe file to response stream
Set appropriate caching and expiry headers
β ANTI-PATTERNS (3)
Buffering full file in memory
Not supporting resume on failure
Blocking event loop during read
π» CODE HINTS (1)
res.pipe(fs.createReadStream(path))
FEEDBACK_AND_CANCEL_IN_UI
When user downloads initiated file from web UI
β
RULES (3)
Show size and time estimates
Expose cancel button for async downloads
Handle retry logic on failure
β ANTI-PATTERNS (3)
No visual feedback for download
Blocking page UI while downloading
No cancel capability for long downloads
π» CODE HINTS (1)
xhr.onprogress = e => updateBar(e.loaded / e.total)
CONTENT_DISPOSITION_AND_FILENAME_CONTROL
When download file name or display behavior matters
β
RULES (3)
Set Content-Disposition header
Escape special characters in filename
Support inline display where applicable
β ANTI-PATTERNS (3)
Serving without filename header
Letting browser guess file type
Inconsistent file names across OS
π» CODE HINTS (1)
Content-Disposition: attachment; filename="report.csv"
MOBILE_DOWNLOAD_COMPATIBILITY
When supporting downloads on iOS/Android browsers
β
RULES (3)
Use blob URLs for JS-initiated files
Test on Safari and Chrome mobile
Avoid forcing download of unsupported formats
β ANTI-PATTERNS (3)
Using desktop-only download strategies
Blocking default behavior on anchor
Expecting file system access on mobile
π» CODE HINTS (1)
const link = URL.createObjectURL(blob); window.open(link)
π§ͺ VALIDATION
Test downloads on various devices, with and without auth. Simulate large files, retry logic, filename variations, and stream/cancel behavior.
#230Matrix 230 β Chunking Matrix6 cells18 rules18 anti6 hints
Define strategies for splitting and reassembling data into manageable chunks to support large transfers, parallelism, and fault-tolerant processing.
chunking_strategychunk_size_determinationordering_and_indexingerror_handling_and_retriesreassembly_pointformat_standardization
FIXED_SIZE_CHUNKS_FOR_STREAMING
When transmitting large files over network
β
RULES (3)
Use fixed-size (e.g. 1MB) binary chunks
Align chunk boundaries with protocol limits
Track total size and number of parts
β ANTI-PATTERNS (3)
Sending entire file in one blob
Using inconsistent chunk sizes
Not signaling end-of-stream
π» CODE HINTS (1)
readStream().slice(i * size, (i+1) * size)
DYNAMIC_CHUNKING_FOR_VARIABLE_DATA
When input data size is unknown or highly variable
β
RULES (3)
Monitor stream pressure or latency
Adjust chunk size dynamically
Avoid over-fragmentation
β ANTI-PATTERNS (3)
Fixing chunk size without runtime feedback
Changing size mid-transmission without signaling
Letting metadata explode
π» CODE HINTS (1)
adjustChunkSize(latencyMetrics)
CHUNK_INDEXING_AND_SEQUENCE_IDS
When order of chunks must be preserved
β
RULES (3)
Include sequence ID in each chunk
Buffer out-of-order arrivals
Validate all parts before merge
β ANTI-PATTERNS (3)
Assuming in-order delivery
Merging on arrival without index
Lacking validation of completeness
π» CODE HINTS (1)
chunk = { seq: i, total: n, data: ... }
RETRYABLE_CHUNK_TRANSMISSION
When chunk delivery may fail in unreliable networks
β
RULES (3)
Track acknowledged chunks
Retry failed chunks only
Cap retry attempts and backoff
β ANTI-PATTERNS (3)
Retrying entire transfer on 1 chunk fail
Ignoring partial failure
Retry storms with no backoff
π» CODE HINTS (1)
if (!acked[chunk.id]) retry(chunk)
REASSEMBLY_AT_TARGET_LAYER
When chunks need to be joined into usable asset
β
RULES (3)
Select reassembly point: client, proxy, or server
Enforce strict schema for join
Checksum final result for integrity
β ANTI-PATTERNS (3)
Merging at unintended layer
Letting client send partial merge
Skipping verification step
π» CODE HINTS (1)
chunks.sort(bySeq).join(); verifyChecksum(fullFile)
CHUNK_FORMAT_AND_ENVELOPE
When transmitting chunks across diverse systems
β
RULES (3)
Wrap each chunk in standard envelope
Include metadata like ID, type, size
Support compression and encryption if needed
β ANTI-PATTERNS (3)
Sending raw binary with no framing
No versioning or content-type markers
Mixing multiple formats in stream
π» CODE HINTS (1)
{ header: { id, seq, type }, body: data }
π§ͺ VALIDATION
Transmit files and records using chunked methods. Simulate network drops, reordering, and partial loss. Confirm retries, reassembly, and validation all succeed.
#231Matrix 231 β Background IO Matrix6 cells18 rules18 anti6 hints
Define how and when to perform background IO operations in client or server apps while minimizing disruption and ensuring consistency.
io_trigger_timingvisibility_scoperesource_priorityexecution_isolationcancellation_policyerror_tolerance_level
DEFERRED_PREFETCH_AFTER_IDLE
When preloading low-priority data during user inactivity
β
RULES (3)
Use requestIdleCallback or equivalent
Prefetch only when app is stable
Avoid contention with critical resources
β ANTI-PATTERNS (3)
Fetching aggressively during interaction
Blocking important UI updates
Prefetching without user need
π» CODE HINTS (1)
requestIdleCallback(() => fetch(...))
SILENT_BACKGROUND_SYNC_LOOP
When syncing data quietly in the background
β
RULES (3)
Throttle frequency to avoid load
Retry failed syncs with backoff
Pause on tab blur or low power mode
β ANTI-PATTERNS (3)
Constant polling without control
No error awareness or alerting
Updating state mid-user edit
π» CODE HINTS (1)
setInterval(syncData, 60000);
BACKGROUND_UPLOAD_WITH_QUEUEING
When uploading large or delayed content (e.g., images)
β
RULES (3)
Use job queue or indexedDB buffer
Provide offline persistence until success
Notify user on permanent failure
β ANTI-PATTERNS (3)
Uploading in main thread directly
Dropping uploads on tab close
Assuming success without confirmation
π» CODE HINTS (1)
enqueueUpload(blob); processQueue()
SERVER_SIDE_LOW_PRIORITY_JOBS
When processing IO-bound work thatβs non-blocking (e.g., logging)
β
RULES (3)
Dispatch jobs to async worker or message queue
Ensure isolation from user-visible flow
Allow retries and monitoring
β ANTI-PATTERNS (3)
Running heavy IO inline with request
Blocking response on log flush
Failing silently on job failure
π» CODE HINTS (1)
queue.push('event_log', { ... })
PARALLEL_FETCH_WITH_PRIORITY_HINT
When loading multiple resources but some can be deprioritized
β
RULES (3)
Use fetch priority hints or custom scheduler
Abort or defer lower-priority on congestion
Track load order for observability
β ANTI-PATTERNS (3)
Loading everything with same priority
No backpressure management
Letting background fetch delay interactive UI
π» CODE HINTS (1)
fetch(url, { priority: 'low' })
CANCELABLE_BACKGROUND_IO_TASKS
When background IO may become irrelevant (e.g., user navigation)
β
RULES (3)
Use AbortController or worker termination
Listen for unmount/navigation events
Clean up pending requests on teardown
β ANTI-PATTERNS (3)
Letting background IO finish after user leaves
Leaking memory or open connections
Retrying canceled requests
π» CODE HINTS (1)
const ctrl = new AbortController(); ctrl.abort()
π§ͺ VALIDATION
Test under load and network fluctuation. Confirm tasks defer, abort, and retry appropriately without blocking primary interaction paths.
#232Matrix 232 β Offline Mode Matrix6 cells18 rules18 anti6 hints
Define strategies for building reliable offline-first experiences in web or mobile apps, including caching, sync, and user feedback.
connectivity_detection_methoddata_persistence_strategyui_feedback_mechanismsync_defer_policyconflict_avoidancefallback_behavior
OFFLINE_DETECTION_AND_STATE_TRACKING
When user loses network connectivity mid-session
β
RULES (3)
Listen to navigator.onLine changes
Track last known online timestamp
Expose offline indicator in UI
β ANTI-PATTERNS (3)
Relying solely on failed requests
Assuming first failure = offline
Lack of visual state change
π» CODE HINTS (1)
window.addEventListener('offline', () => setAppOffline(true))
LOCAL_WRITE_CACHE_AND_BUFFER
When user performs write actions while offline
β
RULES (3)
Use IndexedDB or localStorage for persistence
Tag buffered writes with timestamp
Expose retry/resume API
β ANTI-PATTERNS (3)
Dropping writes on submit
Letting writes mutate state without commit
Blocking user input
π» CODE HINTS (1)
offlineQueue.push({ type: 'save', data })
UI_FEEDBACK_DURING_OFFLINE_MODE
When user interacts with app in offline state
β
RULES (3)
Show offline banner or badge
Disable or ghost blocked features
Display success state for locally buffered actions
β ANTI-PATTERNS (3)
Letting user think changes are live
Showing spinners that never resolve
Silent failures on input
π» CODE HINTS (1)
showBanner('You are offline. Changes will sync later.')
PRELOAD_AND_CACHE_FOR_OFFLINE_USE
When app should remain usable during connectivity loss
β
RULES (3)
Use service workers for asset caching
Prefetch user-specific data on login
Store recent records in local DB
β ANTI-PATTERNS (3)
Assuming CDNs are always reachable
No fallback for failed API calls
Caching UI without state
π» CODE HINTS (1)
caches.open('app').addAll(['/index.html', '/styles.css'])
RECONNECTION_AND_RECONCILIATION_POLICY
When app regains network connectivity
β
RULES (3)
Flush write queue in order
Refetch stale data
Detect and handle conflicts
β ANTI-PATTERNS (3)
Blind overwrite of server state
Ignoring locally changed records
Missing user-visible sync feedback
π» CODE HINTS (1)
processOfflineQueue(); refreshFromServer()
OFFLINE_MODE_FALLBACK_FLOW
When core features are unavailable due to offline state
β
RULES (3)
Redirect to offline-compatible views
Provide export/download option when sync fails
Explain limitations without blame
β ANTI-PATTERNS (3)
Crashing on unavailable API
Blank screen without explanation
Forcing logout during offline
π» CODE HINTS (1)
if (!online) navigate('/offline')
π§ͺ VALIDATION
Simulate full offline state and interaction. Verify local buffering, visual cues, disabled flows, cache hit ratio, and recovery accuracy after reconnection.
#233Matrix 233 β Sync on Reconnect Matrix6 cells18 rules18 anti6 hints
Define strategies to safely synchronize state after reconnection, resolving conflicts and ensuring data integrity without user confusion.
reconnect_detectionsync_trigger_scopeconflict_resolution_methodsync_feedback_displaystaleness_detection_strategysync_retry_policy
RECONNECT_EVENT_HOOK
When app regains network connectivity
β
RULES (3)
Use navigator.onLine or socket.on('reconnect')
Debounce repeated reconnects
Verify backend state before applying queued actions
β ANTI-PATTERNS (3)
Firing sync before network stable
Flooding with retries on flapping connection
Letting offline data override newer remote state
π» CODE HINTS (1)
window.addEventListener('online', syncNow)
SCOPED_DATA_SYNC_STRATEGY
When only part of app data is affected
β
RULES (3)
Track dirty flags per entity type
Sync only recently changed views
Defer cold or unused views
β ANTI-PATTERNS (3)
Global revalidation on every reconnect
Syncing inactive modules unnecessarily
Failing to isolate active vs passive state
π» CODE HINTS (1)
sync({ scope: 'chat', changedOnly: true })
CONFLICT_RESOLUTION_WITH_VERSION_CHECK
When local data may be outdated or changed concurrently
β
RULES (3)
Compare updatedAt timestamps or content hashes
Show merge dialog or auto-resolve when safe
Log all conflicts for review
β ANTI-PATTERNS (3)
Last-write-wins on reconnect blindly
Applying both changes without detection
Ignoring silent divergence
π» CODE HINTS (1)
if (local.updatedAt < remote.updatedAt) overwrite()
USER_FEEDBACK_DURING_RECONNECT_SYNC
When data sync starts automatically on reconnect
β
RULES (3)
Show loading banner or sync status badge
Confirm when sync completes
Display count of updated or failed items
β ANTI-PATTERNS (3)
Running sync silently
Overwriting state without notice
Blocking UI with indefinite spinner
π» CODE HINTS (1)
setSyncStatus('Reconnecting...')
STALENESS_DETECTION_ON_RECONNECT
When resuming from long offline period
β
RULES (3)
Compare timestamps vs current server time
Mark stale items visually or reload silently
Purge cache if outside freshness threshold
β ANTI-PATTERNS (3)
Assuming cached data is still valid
No TTL or last-sync tracking
Reloading all data unnecessarily
π» CODE HINTS (1)
if (Date.now() - lastSync > threshold) refresh()
SYNC_RETRY_POLICY_ON_FAILURE
When reconnect sync fails due to server or conflict
β
RULES (3)
Backoff with increasing delay
Allow manual retry from user
Abort after max attempts and notify
β ANTI-PATTERNS (3)
Infinite retry loop
No logging of failure
Retrying same payload without correction
π» CODE HINTS (1)
retry(sync, { attempts: 3, backoff: true })
π§ͺ VALIDATION
Simulate long disconnection and sync sequence. Introduce conflict, observe resolution, retry behavior, and user-facing feedback. Confirm data integrity and logging.
#234Matrix 234 β External Service Failure Matrix6 cells18 rules18 anti6 hints
Define how to handle partial or total failure of dependent services and APIs, including retries, user messaging, fallbacks, and incident logging.
failure_detection_methoduser_impact_scoperetry_and_backoff_strategyfallback_behaviorerror_reporting_and_loggingresilience_tuning
HTTP_5XX_RETRY_AND_BACKOFF
When upstream service returns 500-series errors
β
RULES (3)
Use capped exponential backoff
Log incident metadata
Surface degraded state to monitoring
β ANTI-PATTERNS (3)
Retrying instantly in loop
Assuming failure is always transient
Hiding error from ops dashboards
π» CODE HINTS (1)
retry(fetch, { backoff: true, max: 3 })
TIMEOUTS_AND_DEGRADATION_MODE
When external call times out after delay
β
RULES (3)
Set timeout ceiling (e.g., 3s)
Load degraded version or stub
Queue request retry in background
β ANTI-PATTERNS (3)
Waiting indefinitely
Freezing UI without feedback
Discarding response on timeout
π» CODE HINTS (1)
setTimeout(reject, 3000)
SERVICE_UNAVAILABLE_USER_MESSAGING
When external integration fails visibly to user
β
RULES (3)
Use plain language and suggest next steps
Offer retry or defer option
Track frequency of surfaced errors
β ANTI-PATTERNS (3)
Displaying raw exception message
Blaming third-party vendor
Showing generic failure without action
π» CODE HINTS (1)
showMessage('This feature is temporarily unavailable. Try later.')
FALLBACK_TO_CACHE_OR_STUB
When data cannot be loaded from API
β
RULES (3)
Use cache if valid
Show stub or loading skeleton with disclaimer
Mark view as stale or read-only
β ANTI-PATTERNS (3)
Showing blank view
Crashing app on missing data
Pretending data is current
π» CODE HINTS (1)
if (!liveData) render(cachedData)
DEGRADED_STATE_LOGGING_AND_ALERTING
When external failures affect UX or business flow
β
RULES (3)
Log error category and timestamp
Attach user/session metadata
Trigger alerts for SLA violation
β ANTI-PATTERNS (3)
Relying on silent failover
Logging only after retries exhausted
Missing traceability to UI impact
π» CODE HINTS (1)
log.error('partner_api_down', { user, route, severity: 'major' })
RESILIENCE_TUNING_PER_SERVICE_TIER
When integrating with multiple 3rd-party APIs
β
RULES (3)
Classify partners as critical vs optional
Use circuit breakers for flaky APIs
Cap retry intensity based on risk
β ANTI-PATTERNS (3)
Applying same logic to all services
Keeping broken integrations silently active
Failing open on sensitive endpoints
π» CODE HINTS (1)
if (partner.tier === 'low') disableTemporarily()
π§ͺ VALIDATION
Simulate partner failure conditions (timeouts, 503s). Confirm retries, fallback display, logging behavior, and alert thresholds per service tier.
#235Matrix 235 β Fallback Integration Matrix6 cells18 rules18 anti6 hints
Define how and when to use fallback services or methods when primary integrations fail, including compatibility, switching logic, and risk management.
fallback_trigger_conditionswitching_strategycompatibility_alignmentuser_awareness_levellogging_and_traceabilitysecurity_and_data_consistency
MANUAL_USER_INITIATED_FALLBACK
When user sees failure and opts to retry with alternative
β
RULES (3)
Offer retry with fallback option in UI
Label alternate provider or method
Preserve user state across attempts
β ANTI-PATTERNS (3)
Switching silently
Forcing fallback without context
Resetting form on retry
π» CODE HINTS (1)
showFallbackCTA('Try alternate method')
AUTOMATIC_SWITCH_ON_STATUS_CODE
When primary API returns error and backup is available
β
RULES (3)
Detect 503, 504, or timeout
Switch to backup endpoint programmatically
Log failover reason and timing
β ANTI-PATTERNS (3)
Retrying primary too long before fallback
Missing logging of which provider served data
No alert on repeated fallback
π» CODE HINTS (1)
if (status === 503) use(fallbackProvider)
DATA_FORMAT_ALIGNMENT_LAYER
When fallback source has different payload format
β
RULES (3)
Map fields to internal schema
Handle missing or renamed fields
Log data source for auditing
β ANTI-PATTERNS (3)
Assuming identical structure
Propagating fallback-specific quirks
Skipping schema validation
π» CODE HINTS (1)
transform(fallbackResponse).toStandardModel()
FALLBACK_USAGE_FEEDBACK
When user interacts with fallback data
β
RULES (3)
Label fallback data in UI (when critical)
Log fallback path to client logs
Allow retry of primary if restored
β ANTI-PATTERNS (3)
Pretending fallback = original
Blocking user retry
Exposing fallback path unnecessarily
π» CODE HINTS (1)
tagContent('source:mirror-provider')
TEMPORARY_CACHE_FILL_FROM_FALLBACK
When fallback is slower or has quota limits
β
RULES (3)
Write-through to local cache
Set short TTL for fallback content
Log that cache origin is fallback
β ANTI-PATTERNS (3)
Always fetching fallback for same content
Caching stale or unverified data
Treating fallback as permanent source
π» CODE HINTS (1)
fallbackResult.cached = true; cache.set(key, fallbackResult)
DATA_ISOLATION_AND_INTEGRITY_CHECKS
When fallback source may be less trusted
β
RULES (3)
Run strict validation on fallback input
Flag entries with origin tag
Avoid merge into core dataset without review
β ANTI-PATTERNS (3)
Letting fallback data flow to persistent store directly
Failing to isolate riskier sources
Trusting fallback uptime blindly
π» CODE HINTS (1)
if (source === 'fallback') validateStrict(fallbackData)
π§ͺ VALIDATION
Trigger failover to fallback in test scenarios. Check user awareness, data integrity, cache effect, and reversion behavior after primary restoration.
#236Matrix 236 β Contract Testing Matrix6 cells18 rules18 anti6 hints
Define how to ensure stability and trust in service contracts between producers and consumers, across build-time and run-time boundaries.
contract_definition_locationconsumer_validation_timingproducer_enforcement_strategyversioning_and_compatibilitytest_environment_alignmentfailure_handling_protocol
CONSUMER_DRIVEN_CONTRACTS
When frontend or API consumer defines expectations
β
RULES (3)
Define request/response shape in consumer repo
Use mocks or simulators for testing
Push contract to central registry
β ANTI-PATTERNS (3)
Relying on ad-hoc assumptions
Skipping edge case definition
No sharing back to producer
π» CODE HINTS (1)
pact.define('GET /user', { expectedResponse: ... })
PRODUCER_CONTRACT_VALIDATION_PIPELINE
When backend validates contracts against test data
β
RULES (3)
Pull consumer contracts in CI
Run contract verifier on endpoint mocks
Fail build if regression detected
β ANTI-PATTERNS (3)
Testing only during staging
Manual verification
Assuming contract coverage
π» CODE HINTS (1)
pactVerifier.verify({ provider: 'API' })
CONTRACT_VERSIONING_AND_COMPAT_LAYER
When multiple consumers rely on different contract shapes
β
RULES (3)
Tag contract versions
Deprecate with policy timeline
Gate incompatible changes behind version
β ANTI-PATTERNS (3)
Overwriting contract in place
Breaking consumers silently
No version rollback mechanism
π» CODE HINTS (1)
contract.setVersion('v2')
RUNTIME_SCHEMA_ENFORCEMENT
When runtime requests/responses must match contract
β
RULES (3)
Validate payloads against schema at runtime
Log and quarantine violations
Allow opt-in strict mode for critical flows
β ANTI-PATTERNS (3)
Allowing unexpected fields silently
Logging only without blocking
No alerting on schema mismatch
π» CODE HINTS (1)
ajv.validate(schema, response)
SHARED_SANDBOX_AND_FAKE_SERVICES
When consumer and producer test in isolated environments
β
RULES (3)
Deploy fake provider/consumer for test suite
Mount shared sandbox routes
Tag tests with contract version
β ANTI-PATTERNS (3)
Testing against real prod endpoints
No consistency between test data
Breaking contract during QA cycle
π» CODE HINTS (1)
mountFakeProvider('/sandbox/api')
FAILURE_POLICY_AND_RECOVERY
When contract test fails in CI or runtime
β
RULES (3)
Block builds on regressions
Alert relevant teams on runtime issues
Allow override with justification
β ANTI-PATTERNS (3)
Silently skipping failing tests
No link between failure and code owner
Allowing override without trace
π» CODE HINTS (1)
requireJustification('override_contract_violation')
π§ͺ VALIDATION
Simulate breaking and non-breaking changes across versions. Run contract suite in CI and runtime. Observe failure behavior, rollback, and alert propagation.
#237Matrix 237 β API Versioning Matrix6 cells18 rules18 anti6 hints
Define strategies for maintaining, upgrading, and deprecating versions of APIs while preserving backward compatibility and clear communication.
version_locationchange_type_classificationcompatibility_policyconsumer_migration_supportdeprecation_communicationruntime_enforcement
URL_VERSIONING_CONVENTION
When versioning via API endpoint path
β
RULES (3)
Use /v1/, /v2/ in base path
Avoid mixing multiple versions in same path
Reflect contract differences in docs
β ANTI-PATTERNS (3)
Hiding version in query string only
Switching contract under same URL
Failing to version breaking changes
π» CODE HINTS (1)
GET /api/v2/users
SEMVER_FOR_CONTRACT_CHANGES
When tracking schema and behavior over time
β
RULES (3)
Follow MAJOR.MINOR.PATCH format
Increment MAJOR for breaking changes
Document changes per release
β ANTI-PATTERNS (3)
Skipping version bump on behavior shift
Letting PATCH change contract
Omitting version from changelog
π» CODE HINTS (1)
api.version = '2.1.0'
BACKWARD_COMPATIBILITY_ENFORCEMENT
When deploying updates to existing APIs
β
RULES (3)
Validate schema compatibility
Use feature flags for conditional behavior
Deprecate gradually with shadow mode
β ANTI-PATTERNS (3)
Changing required fields abruptly
Removing properties without notice
Breaking consumers during rollout
π» CODE HINTS (1)
if (version >= 2) useNewSchema()
CONSUMER_VERSION_NEGOTIATION
When different clients support different API versions
β
RULES (3)
Allow client to specify version via header or URL
Respond with compatible version or error
Log version usage statistics
β ANTI-PATTERNS (3)
Forcing latest version on all clients
Ignoring version in request
Failing silently on mismatch
π» CODE HINTS (1)
Accept: application/vnd.myapi.v2+json
DEPRECATION_ANNOUNCEMENT_CHANNELS
When sunsetting an older API version
β
RULES (3)
Announce deprecation in response headers
Email affected partners with timeline
Provide upgrade migration guide
β ANTI-PATTERNS (3)
Deprecating silently
Changing TTL without notice
Removing version without fallback
π» CODE HINTS (1)
Deprecation: true
Sunset: 2024-12-31
VERSION_BLOCKING_AND ROUTING
When unsupported or risky version is requested
β
RULES (3)
Reject unknown versions with HTTP 400
Route traffic based on version
Log rejected version attempts
β ANTI-PATTERNS (3)
Defaulting silently to latest
Processing invalid versions without warning
Mismatched logic between routing and docs
π» CODE HINTS (1)
if (!supported(version)) return 400
π§ͺ VALIDATION
Simulate versioned calls from multiple consumers. Validate correct fallback, migration notice, schema enforcement, and backward-compatible logic.
#238Matrix 238 β Integration Security Matrix6 cells18 rules18 anti6 hints
Define security best practices for integrating with third-party services and APIs, covering authentication, authorization, validation, and trust boundaries.
auth_methodscope_granularityinput_validation_layersecret_handlingtrust_boundary_isolationlogging_and_alerting_sensitivity
TOKEN_BASED_AUTH_WITH_SCOPES
When authenticating outbound API requests
β
RULES (3)
Use OAuth2 or JWT with defined scopes
Rotate tokens regularly
Avoid static API keys when possible
β ANTI-PATTERNS (3)
Embedding secrets in client-side code
Using root tokens for all access
Failing to expire credentials
π» CODE HINTS (1)
Authorization: Bearer <scoped_token>
ENDPOINT_WHITELISTING_AND_FIREWALL_RULES
When calling sensitive services
β
RULES (3)
Apply IP allowlists
Use VPC or private service access
Log all denied egress attempts
β ANTI-PATTERNS (3)
Allowing open outbound internet
Using DNS names without verification
No restriction on port or protocol
π» CODE HINTS (1)
egress.allow = ['api.trusted.com']
INPUT_VALIDATION_ON_ALL_INTEGRATION_PATHS
When accepting input from integrated systems
β
RULES (3)
Validate payloads against schema
Sanitize user-controlled inputs
Enforce max lengths and enum values
β ANTI-PATTERNS (3)
Assuming internal systems are trusted
Validating only at UI layer
Not checking optional nested fields
π» CODE HINTS (1)
validate(req.body, integrationSchema)
SECRET_STORAGE_AND_ROTATION_POLICY
When handling shared secrets with partners
β
RULES (3)
Store secrets in vault or secret manager
Use per-integration keys
Rotate on interval or upon suspicion
β ANTI-PATTERNS (3)
Hardcoding secrets in source
Sharing same secret across tenants
Lack of audit trail for access
π» CODE HINTS (1)
secrets.get('partner-api-key')
BOUNDARY_ISOLATION_AND_SANDBOXING
When invoking untrusted or variable services
β
RULES (3)
Use execution sandbox or proxy isolation
Run unknown code in jailed environment
Separate integration from core services
β ANTI-PATTERNS (3)
Calling external code from core threads
No resource limits or quotas
Combining trusted and untrusted data paths
π» CODE HINTS (1)
invokeInSandbox(fn, payload)
INTEGRATION_LOGGING_AND_ALERTING_HYGIENE
When auditing external calls and responses
β
RULES (3)
Scrub PII and credentials from logs
Sample logs based on risk
Trigger alerts on suspicious patterns
β ANTI-PATTERNS (3)
Logging full request/response by default
Storing long-lived tokens in logs
No alerting on repeated failures
π» CODE HINTS (1)
log.info('partner_response', sanitize(response))
π§ͺ VALIDATION
Perform integration scans. Trigger failures and analyze logs, alerts, and token scope enforcement. Verify secrets are stored, rotated, and protected.
#239Matrix 239 β Secrets Handling Matrix6 cells18 rules18 anti6 hints
Define how to manage secrets (API keys, tokens, credentials) across environments and services securely, minimizing risk of leakage or misuse.
secret_sourcescope_and_lifetimestorage_locationruntime_access_controlrotation_policyleak_detection_mechanism
ENV_VAR_SECRETS_IN_BACKEND_ONLY
When accessing static secrets on server side
β
RULES (3)
Inject via environment variables
Exclude from build output
Log usage without value exposure
β ANTI-PATTERNS (3)
Putting secrets in config.js
Referencing env vars in client bundles
Logging full secret string
π» CODE HINTS (1)
process.env.STRIPE_SECRET_KEY
SECRET_MANAGER_WITH_ACCESS_POLICIES
When storing dynamic secrets across microservices
β
RULES (3)
Use HashiCorp Vault, AWS Secrets Manager, or similar
Define role-based access per service
Log access requests and denials
β ANTI-PATTERNS (3)
Using file-based secrets in production
Letting all services access all secrets
Skipping denial audits
π» CODE HINTS (1)
vault.read('service/db-creds')
TEMPORARY_SESSIONS_AND_EPHEMERAL_KEYS
When authenticating users or one-time flows
β
RULES (3)
Expire keys within minutes
Restrict usage to IP or session context
Store in memory or secure cookie
β ANTI-PATTERNS (3)
Long-lived session tokens
Tokens that work across browsers
Writing temp keys to disk
π» CODE HINTS (1)
setCookie('session', token, { maxAge: 300 })
ROLE_BASED_RUNTIME_ACCESS
When services or scripts request secret at runtime
β
RULES (3)
Use runtime identity or IAM roles
Tag secrets with consumer role
Block access outside policy context
β ANTI-PATTERNS (3)
Granting broad access via root creds
No enforcement of runtime identity
Caching secrets in global scope
π» CODE HINTS (1)
assumeRole('upload-worker')
SECRET_ROTATION_AND_REVOCATION_HOOKS
When secrets need to be changed periodically
β
RULES (3)
Define TTL and rotation window
Notify affected services
Revoke old version on use
β ANTI-PATTERNS (3)
Manually rotating in emergencies
Letting old secrets linger post-deploy
Skipping alert on use of expired key
π» CODE HINTS (1)
rotateSecret('db-token') β notify(['app1','app2'])
LEAK_DETECTION_AND_SCAN_PIPELINES
When secrets may accidentally leak into code or logs
β
RULES (3)
Scan git commits for patterns
Alert on regex hits in logs
Invalidate exposed secrets immediately
β ANTI-PATTERNS (3)
Relying solely on reviews
Skipping post-commit scans
Keeping exposed secrets active
π» CODE HINTS (1)
gitleaks --repo ./src
π§ͺ VALIDATION
Simulate secret usage across all flows. Rotate keys, scan for leaks, and verify access control and isolation. Audit log presence and security posture across environments.
#240Matrix 240 β IO Observability Matrix6 cells18 rules18 anti6 hints
Define strategies for tracking, measuring, and troubleshooting IO operations across internal and external systems, with visibility into flow, timing, and failures.
telemetry_capture_pointmetrics_collectedcorrelation_and_traceabilityaggregation_scopealerting_and_thresholdsdeveloper_accessibility
API_LATENCY_AND_THROUGHPUT_METRICS
When monitoring external API performance
β
RULES (3)
Collect avg, p95, max latency
Measure requests per minute
Tag by endpoint and status
β ANTI-PATTERNS (3)
Logging only failures
Skipping high-percentile latency
Ignoring burst traffic
π» CODE HINTS (1)
recordMetric('api.latency', { path, p95 })
DISTRIBUTED_TRACING_ACROSS_SERVICES
When debugging multi-service IO path
β
RULES (3)
Inject trace ID in all outbound requests
Use consistent headers like X-Request-ID
Log timing at each hop
β ANTI-PATTERNS (3)
Creating new ID per hop
No parent-child span relationships
Logging without ID linkage
π» CODE HINTS (1)
span = tracer.startSpan('db.query')
REALTIME_FAILURE_RATE_ALERTING
When error rate spikes suddenly
β
RULES (3)
Monitor 4xx/5xx rate per endpoint
Set dynamic thresholds with baseline
Include contextual metadata in alert
β ANTI-PATTERNS (3)
Alerting only on total downtime
No segmentation by service
Ignoring retry/fallback events
π» CODE HINTS (1)
if errorRate(path) > threshold then alertTeam(path)
AGGREGATED_IO_HEALTH_DASHBOARDS
When product managers and ops need global view
β
RULES (3)
Display latency, error, retry, fallback rates
Segment by integration domain
Update in near real-time
β ANTI-PATTERNS (3)
Only raw log access without graphs
Dashboards for developers only
No business-level abstraction
π» CODE HINTS (1)
Grafana.panel('IO Heatmap')
DEVELOPER_QUERY_AND TRACE_TOOLS
When investigating integration issues locally
β
RULES (3)
Expose searchable logs via dev portal
Provide CLI access with filters
Tag with team or feature owner
β ANTI-PATTERNS (3)
Only ops have observability tools
No link from error to trace
No access in staging/dev
π» CODE HINTS (1)
trace.lookup({ spanId }).open()
SYNTHETIC_PROBES_AND_HEALTH_CHECKS
When needing baseline monitoring of integrations
β
RULES (3)
Run synthetic checks hourly
Use real endpoints with test data
Track failures and performance over time
β ANTI-PATTERNS (3)
Only checking availability, not behavior
No test coverage of fallback path
Treating synthetic pass = user success
π» CODE HINTS (1)
probe('/search?q=test').expect(200)
π§ͺ VALIDATION
Simulate load, latency, and failure. Confirm traces span hops, alerts trigger on spike, and dashboards reflect real IO state. Trace from user event to service response.