anti-slop-engineering 1.2.1 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.skills.json +1 -1
- package/README.md +57 -4
- package/SKILL.md +6 -1
- package/bin/cli.js +24 -3
- package/dist/bin/anti-slop-rust +0 -0
- package/dist/bin/toil-guard +0 -0
- package/install.sh +8 -2
- package/marketplace.json +1 -1
- package/package.json +3 -1
- package/references/anti-pattern-catalog.md +1 -0
- package/scripts/bump_version.py +276 -0
- package/scripts/future_scale_guard.py +197 -0
- package/scripts/paranoid_guard.py +201 -0
- package/services/anti-slop-rust/Cargo.lock +1 -1
- package/services/anti-slop-rust/Cargo.toml +1 -1
- package/services/toil-guard-go/pkg/model/types.go +1 -1
- package/services/toil-guard-go/pkg/server/server.go +1 -1
- package/skills/future-scale-gate/SKILL.md +101 -0
- package/skills/future-scale-gate/evals/scenarios.json +78 -0
- package/skills/future-scale-gate/examples/runtime-envelope-record.json +61 -0
- package/skills/future-scale-gate/references/foundation-method.md +73 -0
- package/skills/future-scale-gate/references/record-contract.md +47 -0
- package/skills/future-scale-gate/usecases/architect.md +13 -0
- package/skills/future-scale-gate/usecases/review.md +10 -0
- package/skills/paranoid-principal-architect/Playbook/paranoid_principal_architect_playbook.md +92 -0
- package/skills/paranoid-principal-architect/SKILL.md +140 -0
- package/skills/paranoid-principal-architect/evals/scenarios.json +112 -0
- package/skills/paranoid-principal-architect/examples/hardened-idempotent-service.ts +177 -0
- package/skills/paranoid-principal-architect/examples/paranoid-architecture-record.json +58 -0
- package/skills/paranoid-principal-architect/references/modern-web-platform.md +134 -0
- package/skills/paranoid-principal-architect/references/scale-concurrency-patterns.md +173 -0
- package/skills/paranoid-principal-architect/references/threat-record-contract.md +130 -0
- package/skills/paranoid-principal-architect/references/zero-trust-security.md +128 -0
- package/skills/paranoid-principal-architect/usecases/architect.md +40 -0
- package/skills/paranoid-principal-architect/usecases/implement.md +28 -0
- package/skills/paranoid-principal-architect/usecases/review.md +51 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Example: Hardened Idempotent Payment & Ledger Service (Day-One 10M Scale & Zero-Trust)
|
|
3
|
+
|
|
4
|
+
import { timingSafeEqual, randomUUID } from "node:crypto";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
// --- 1. Type Branding ---
|
|
8
|
+
declare const __brand: unique symbol;
|
|
9
|
+
export type Brand<T, B> = T & { readonly [__brand]: B };
|
|
10
|
+
|
|
11
|
+
export type UserId = Brand<string, "UserId">;
|
|
12
|
+
export type TenantId = Brand<string, "TenantId">;
|
|
13
|
+
export type PaymentId = Brand<string, "PaymentId">;
|
|
14
|
+
|
|
15
|
+
export function parseUserId(raw: string): UserId {
|
|
16
|
+
if (!/^usr_[a-zA-Z0-9]{24}$/.test(raw)) {
|
|
17
|
+
throw new TypeError(`Invalid UserId format: ${raw}`);
|
|
18
|
+
}
|
|
19
|
+
return raw as UserId;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function parseTenantId(raw: string): TenantId {
|
|
23
|
+
if (!/^ten_[a-zA-Z0-9]{24}$/.test(raw)) {
|
|
24
|
+
throw new TypeError(`Invalid TenantId format: ${raw}`);
|
|
25
|
+
}
|
|
26
|
+
return raw as TenantId;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// --- 2. Boundary Schema Validation (Parse, Don't Validate) ---
|
|
30
|
+
export const ProcessPaymentRequestSchema = z.object({
|
|
31
|
+
idempotencyKey: z.string().uuid("Invalid idempotency key: must be a valid UUID v4"),
|
|
32
|
+
amountInCents: z.number().int().positive().max(10_000_000, "Maximum transaction is $100,000.00"),
|
|
33
|
+
currency: z.enum(["USD", "EUR", "GBP"]),
|
|
34
|
+
recipientUserId: z.string().regex(/^usr_[a-zA-Z0-9]{24}$/, "Invalid recipient user ID format"),
|
|
35
|
+
metadata: z.record(z.string().max(64), z.string().max(256)).optional()
|
|
36
|
+
}).strict(); // Strip and reject any unknown fields
|
|
37
|
+
|
|
38
|
+
export type ProcessPaymentRequest = z.infer<typeof ProcessPaymentRequestSchema>;
|
|
39
|
+
|
|
40
|
+
export interface PaymentDto {
|
|
41
|
+
paymentId: PaymentId;
|
|
42
|
+
amountInCents: number;
|
|
43
|
+
currency: string;
|
|
44
|
+
status: "COMPLETED" | "PENDING";
|
|
45
|
+
createdAt: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface ApiErrorEnvelope {
|
|
49
|
+
correlationId: string;
|
|
50
|
+
code: string;
|
|
51
|
+
message: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// --- 3. Constant-Time Secret Verification ---
|
|
55
|
+
export function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean {
|
|
56
|
+
const expectedHmac = Buffer.from(signature, "hex");
|
|
57
|
+
const actualHmac = Buffer.from(payload + secret, "utf-8"); // Example buffer construction
|
|
58
|
+
if (expectedHmac.length !== actualHmac.length) {
|
|
59
|
+
timingSafeEqual(expectedHmac, expectedHmac); // Balance timing
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
return timingSafeEqual(expectedHmac, actualHmac);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// --- 4. Concurrency & Hot-Key Defense (16-Shard Counter) ---
|
|
66
|
+
const NUM_SHARDS = 16;
|
|
67
|
+
|
|
68
|
+
export function selectShardIndex(resourceId: string): number {
|
|
69
|
+
let hash = 0;
|
|
70
|
+
for (let i = 0; i < resourceId.length; i++) {
|
|
71
|
+
hash = ((hash << 5) - hash) + resourceId.charCodeAt(i);
|
|
72
|
+
hash |= 0;
|
|
73
|
+
}
|
|
74
|
+
return Math.abs(hash) % NUM_SHARDS;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// --- 5. Hardened Payment Service ---
|
|
78
|
+
export interface StorageAdapter {
|
|
79
|
+
getIdempotency(key: string): Promise<PaymentDto | null>;
|
|
80
|
+
saveIdempotency(key: string, result: PaymentDto, ttlSeconds: number): Promise<void>;
|
|
81
|
+
acquireLock(key: string, ttlSeconds: number): Promise<boolean>;
|
|
82
|
+
releaseLock(key: string): Promise<void>;
|
|
83
|
+
recordLedgerEntry(entry: {
|
|
84
|
+
paymentId: PaymentId;
|
|
85
|
+
tenantId: TenantId;
|
|
86
|
+
senderId: UserId;
|
|
87
|
+
recipientId: UserId;
|
|
88
|
+
amountInCents: number;
|
|
89
|
+
currency: string;
|
|
90
|
+
shardIndex: number;
|
|
91
|
+
}): Promise<void>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export class HardenedPaymentService {
|
|
95
|
+
constructor(
|
|
96
|
+
private readonly storage: StorageAdapter,
|
|
97
|
+
private readonly gatewayUrl: string
|
|
98
|
+
) {}
|
|
99
|
+
|
|
100
|
+
public async processPaymentWithIdempotency(
|
|
101
|
+
idempotencyKey: string,
|
|
102
|
+
untrustedInput: unknown,
|
|
103
|
+
callerTenantId: TenantId,
|
|
104
|
+
callerUserId: UserId,
|
|
105
|
+
correlationId = randomUUID()
|
|
106
|
+
): Promise<PaymentDto> {
|
|
107
|
+
// Phase A: Boundary Validation
|
|
108
|
+
const parsed = ProcessPaymentRequestSchema.parse({
|
|
109
|
+
...(typeof untrustedInput === "object" && untrustedInput !== null ? untrustedInput : {}),
|
|
110
|
+
idempotencyKey
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
// Phase B: Idempotency Fast-Path
|
|
114
|
+
const cached = await this.storage.getIdempotency(parsed.idempotencyKey);
|
|
115
|
+
if (cached) {
|
|
116
|
+
return cached;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Phase C: Distributed Concurrency Lock
|
|
120
|
+
const lockAcquired = await this.storage.acquireLock(`lock:pay:${parsed.idempotencyKey}`, 30);
|
|
121
|
+
if (!lockAcquired) {
|
|
122
|
+
throw new Error("CONCURRENT_REQUEST_IN_PROGRESS");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
try {
|
|
126
|
+
// Phase D: Outbound Network Call with Hard Timeout (AbortSignal.timeout)
|
|
127
|
+
const timeoutSignal = AbortSignal.timeout(3000); // 3-second hard SLA bound
|
|
128
|
+
const gatewayResponse = await fetch(`${this.gatewayUrl}/v1/charges`, {
|
|
129
|
+
method: "POST",
|
|
130
|
+
headers: {
|
|
131
|
+
"Content-Type": "application/json",
|
|
132
|
+
"Idempotency-Key": parsed.idempotencyKey,
|
|
133
|
+
"X-Correlation-ID": correlationId
|
|
134
|
+
},
|
|
135
|
+
body: JSON.stringify({
|
|
136
|
+
amount: parsed.amountInCents,
|
|
137
|
+
currency: parsed.currency
|
|
138
|
+
}),
|
|
139
|
+
signal: timeoutSignal
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
if (!gatewayResponse.ok) {
|
|
143
|
+
throw new Error(`GATEWAY_CHARGE_FAILED_${gatewayResponse.status}`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Phase E: Sharded Append-Only Ledger Entry (Never update balances in-place!)
|
|
147
|
+
const paymentId = `pay_${randomUUID().replace(/-/g, "").slice(0, 24)}` as PaymentId;
|
|
148
|
+
const shard = selectShardIndex(callerTenantId);
|
|
149
|
+
|
|
150
|
+
await this.storage.recordLedgerEntry({
|
|
151
|
+
paymentId,
|
|
152
|
+
tenantId: callerTenantId,
|
|
153
|
+
senderId: callerUserId,
|
|
154
|
+
recipientId: parsed.recipientUserId as UserId,
|
|
155
|
+
amountInCents: parsed.amountInCents,
|
|
156
|
+
currency: parsed.currency,
|
|
157
|
+
shardIndex: shard
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// Phase F: Safe DTO Projection (Zero sensitive/internal field leakage)
|
|
161
|
+
const dto: PaymentDto = {
|
|
162
|
+
paymentId,
|
|
163
|
+
amountInCents: parsed.amountInCents,
|
|
164
|
+
currency: parsed.currency,
|
|
165
|
+
status: "COMPLETED",
|
|
166
|
+
createdAt: new Date().toISOString()
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
// Phase G: Persist Idempotent Response (24h TTL)
|
|
170
|
+
await this.storage.saveIdempotency(parsed.idempotencyKey, dto, 86400);
|
|
171
|
+
|
|
172
|
+
return dto;
|
|
173
|
+
} finally {
|
|
174
|
+
await this.storage.releaseLock(`lock:pay:${parsed.idempotencyKey}`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema_version": "1.0",
|
|
3
|
+
"goal": "Operate high-throughput checkout payment mutation service for global flash-sale events",
|
|
4
|
+
"scale_profile": {
|
|
5
|
+
"target_concurrency": 10000000,
|
|
6
|
+
"throughput_rps": 120000,
|
|
7
|
+
"latency_budget_ms": 75
|
|
8
|
+
},
|
|
9
|
+
"threat_pre_mortem": [
|
|
10
|
+
{
|
|
11
|
+
"id": "double-submit-race",
|
|
12
|
+
"threat_class": "race_condition",
|
|
13
|
+
"description": "Users double-click checkout button creating identical charges within a 10ms window",
|
|
14
|
+
"mitigation": "Atomic idempotency key lock in distributed cache with 24h cached payload replay"
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"id": "global-inventory-hotkey",
|
|
18
|
+
"threat_class": "hot_key_contention",
|
|
19
|
+
"description": "100k requests/sec attempt synchronous row update on a single inventory item counter",
|
|
20
|
+
"mitigation": "16-shard counter with uniform random write routing and periodic read rollups"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"id": "downstream-gateway-stall",
|
|
24
|
+
"threat_class": "network_stall",
|
|
25
|
+
"description": "Payment gateway latency surges to 30s during flash-sale peak exhausting socket pools",
|
|
26
|
+
"mitigation": "Non-negotiable AbortSignal.timeout(3000ms) with exponential backoff and full jitter"
|
|
27
|
+
}
|
|
28
|
+
],
|
|
29
|
+
"trust_boundaries": [
|
|
30
|
+
{
|
|
31
|
+
"name": "public-checkout-api",
|
|
32
|
+
"schema_validation": "zod_strict_parse_with_stripped_unknowns",
|
|
33
|
+
"data_layer_ownership": "tenant_and_user_id_scoped_in_sql_where_clause"
|
|
34
|
+
}
|
|
35
|
+
],
|
|
36
|
+
"concurrency_controls": {
|
|
37
|
+
"idempotency": {
|
|
38
|
+
"enabled": true,
|
|
39
|
+
"key_header": "Idempotency-Key",
|
|
40
|
+
"storage": "redis_set_nx_ex_86400"
|
|
41
|
+
},
|
|
42
|
+
"locking_strategy": "sharded_counters"
|
|
43
|
+
},
|
|
44
|
+
"bounded_limits": {
|
|
45
|
+
"max_read_limit": 50,
|
|
46
|
+
"max_payload_bytes": 102400,
|
|
47
|
+
"network_timeout_ms": 3000,
|
|
48
|
+
"backoff_algorithm": "exponential_full_jitter"
|
|
49
|
+
},
|
|
50
|
+
"verdict": {
|
|
51
|
+
"action": "proceed",
|
|
52
|
+
"rationale": "All scale bottlenecks and malicious attack vectors are mitigated with bounded resources and zero-trust controls.",
|
|
53
|
+
"revisit_triggers": [
|
|
54
|
+
"Flash-sale concurrency exceeds 20,000,000 active sessions",
|
|
55
|
+
"Payment gateway changes idempotency header semantics"
|
|
56
|
+
]
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
# Modern Web Platform Standards & Clean Architecture
|
|
2
|
+
|
|
3
|
+
## 1. Native Web Platform Primitives (TC39, WHATWG, W3C)
|
|
4
|
+
|
|
5
|
+
Legacy utility libraries (lodash, moment, axios, deep-clone, querystring) add bundle bloat, security audit overhead, and supply chain exposure. The Paranoid Architect prioritizes native standards:
|
|
6
|
+
|
|
7
|
+
| Legacy / Bloated Pattern | Native Platform Standard | Advantage |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| `axios.get(url, { timeout: 3000 })` | `fetch(url, { signal: AbortSignal.timeout(3000) })` | Zero dependencies, native stream cancellation |
|
|
10
|
+
| `lodash.cloneDeep(obj)` | `structuredClone(obj)` | Native C++ memory cloning, handles circular references |
|
|
11
|
+
| `lodash.groupBy(arr, fn)` | `Object.groupBy(arr, fn)` | Native ECMAScript standard (TC39 Stage 4) |
|
|
12
|
+
| `moment(d).format(...)` | `new Intl.DateTimeFormat(locale, options).format(d)` | Native browser/engine i18n, zero bundle impact |
|
|
13
|
+
| `querystring.parse(str)` | `new URLSearchParams(str)` | Spec-compliant WHATWG URL encoding and parsing |
|
|
14
|
+
| Hand-rolled chunked reader | `ReadableStream` / `TransformStream` | Native Web Streams with automatic backpressure |
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 2. Modern Semantic HTML5 & Accessible UI
|
|
19
|
+
|
|
20
|
+
High-scale web frontends must be universally accessible, resilient, and lightweight:
|
|
21
|
+
|
|
22
|
+
### Modal Architecture: Native `<dialog>`
|
|
23
|
+
Never hand-roll div-based modals with synthetic event listeners and fragile focus loops:
|
|
24
|
+
```html
|
|
25
|
+
<dialog id="confirm-modal" aria-labelledby="modal-title">
|
|
26
|
+
<form method="dialog">
|
|
27
|
+
<h2 id="modal-title">Confirm Deletion</h2>
|
|
28
|
+
<p>This action is irreversible.</p>
|
|
29
|
+
<button type="submit" value="cancel">Cancel</button>
|
|
30
|
+
<button type="submit" value="confirm" autofocus>Confirm</button>
|
|
31
|
+
</form>
|
|
32
|
+
</dialog>
|
|
33
|
+
```
|
|
34
|
+
- Invoking `dialogElement.showModal()` automatically locks interaction to the top layer, traps Tab focus within the dialog, prevents background scroll, and closes on `Escape`.
|
|
35
|
+
- Returns user choice natively through `dialogElement.addEventListener('close', ...)`.
|
|
36
|
+
|
|
37
|
+
### Semantic Controls
|
|
38
|
+
- **Buttons:** Always declare explicit `type="button"` on interactive controls inside forms that are not submit triggers, preventing unintended form submissions.
|
|
39
|
+
- **Collapsible Regions:** Use native `<details>` and `<summary>` instead of synthetic toggle div hierarchies.
|
|
40
|
+
|
|
41
|
+
### Modern CSS Invariants
|
|
42
|
+
- Use `:has()` parent-selectors and Container Queries (`@container`) for modular, component-driven layouts.
|
|
43
|
+
- Always respect user accessibility preferences:
|
|
44
|
+
```css
|
|
45
|
+
@media (prefers-reduced-motion: reduce) {
|
|
46
|
+
*, ::before, ::after {
|
|
47
|
+
animation-duration: 0.01ms !important;
|
|
48
|
+
animation-iteration-count: 1 !important;
|
|
49
|
+
transition-duration: 0.01ms !important;
|
|
50
|
+
scroll-behavior: auto !important;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## 3. Strict Type Discipline & Type Branding
|
|
58
|
+
|
|
59
|
+
TypeScript is not documentation; it is a structural proof system. Loose typing breeds silent runtime corruption.
|
|
60
|
+
|
|
61
|
+
### Prohibitions
|
|
62
|
+
- **Ban `any`:** `any` disables type checking across all downstream consumers.
|
|
63
|
+
- **Ban `@ts-ignore` / `@ts-nocheck`:** Never suppress the compiler.
|
|
64
|
+
- **Ban blind assertions (`input as TargetType`):** Type assertions mask upstream schema mismatches. Use runtime type guards or Zod schema parsers.
|
|
65
|
+
|
|
66
|
+
### Branded Types for Domain Identifiers
|
|
67
|
+
Prevent accidental parameter transposition (e.g. passing an `orgId` where a `userId` is required):
|
|
68
|
+
```typescript
|
|
69
|
+
declare const __brand: unique symbol;
|
|
70
|
+
export type Brand<T, B> = T & { readonly [__brand]: B };
|
|
71
|
+
|
|
72
|
+
export type UserId = Brand<string, "UserId">;
|
|
73
|
+
export type OrganizationId = Brand<string, "OrganizationId">;
|
|
74
|
+
export type Cents = Brand<number, "Cents">;
|
|
75
|
+
|
|
76
|
+
export function createUserId(raw: string): UserId {
|
|
77
|
+
if (!/^usr_[a-zA-Z0-9]{24}$/.test(raw)) {
|
|
78
|
+
throw new TypeError(`Invalid UserId format: ${raw}`);
|
|
79
|
+
}
|
|
80
|
+
return raw as UserId;
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Discriminated Unions for State
|
|
85
|
+
Model domain states as exhaustive discriminated unions:
|
|
86
|
+
```typescript
|
|
87
|
+
export type AsyncState<T> =
|
|
88
|
+
| { status: "idle" }
|
|
89
|
+
| { status: "loading" }
|
|
90
|
+
| { status: "success"; data: T }
|
|
91
|
+
| { status: "error"; code: string; message: string };
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## 4. Structured Error Handling & Zero Meta-Leakage
|
|
97
|
+
|
|
98
|
+
### The Empty Catch Prohibition
|
|
99
|
+
Never swallow exceptions:
|
|
100
|
+
```typescript
|
|
101
|
+
// FATAL DEFECT: Swallowing errors masks silent failures and data corruption
|
|
102
|
+
try {
|
|
103
|
+
await persistRecord();
|
|
104
|
+
} catch (e) {}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Deterministic Error Mapping & Correlation IDs
|
|
108
|
+
Every operational error must map to a standardized machine-readable envelope without leaking database schemas, server paths, or stack traces:
|
|
109
|
+
```typescript
|
|
110
|
+
export interface ApiErrorEnvelope {
|
|
111
|
+
correlationId: string;
|
|
112
|
+
code: string;
|
|
113
|
+
message: string;
|
|
114
|
+
details?: Record<string, unknown>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function handleControllerError(err: unknown, correlationId: string): Response {
|
|
118
|
+
// 1. Log full internal stack trace securely to private logging pipeline
|
|
119
|
+
logger.error({ correlationId, error: err }, "Unhandled request error");
|
|
120
|
+
|
|
121
|
+
// 2. Return clean, unslop, non-leaking payload to the caller
|
|
122
|
+
const envelope: ApiErrorEnvelope = {
|
|
123
|
+
correlationId,
|
|
124
|
+
code: err instanceof DomainError ? err.code : "INTERNAL_SERVER_ERROR",
|
|
125
|
+
message: err instanceof DomainError ? err.message : "An unexpected error occurred."
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const status = err instanceof DomainError ? err.httpStatus : 500;
|
|
129
|
+
return new Response(JSON.stringify(envelope), {
|
|
130
|
+
status,
|
|
131
|
+
headers: { "Content-Type": "application/json" }
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
```
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# Scale & Concurrency Patterns (Day-One 10M Concurrent Users)
|
|
2
|
+
|
|
3
|
+
## 1. Mathematical Modeling & Little's Law
|
|
4
|
+
|
|
5
|
+
Under the 10,000,000 Concurrent Users Axiom, capacity and latency cannot be left to intuition. System concurrency is governed by Little's Law:
|
|
6
|
+
|
|
7
|
+
$$L = \lambda \times W$$
|
|
8
|
+
|
|
9
|
+
Where:
|
|
10
|
+
- $L$ = Number of concurrent requests in-flight across the system
|
|
11
|
+
- $\lambda$ = Arrival rate (throughput in requests per second)
|
|
12
|
+
- $W$ = Average response time (latency in seconds)
|
|
13
|
+
|
|
14
|
+
### Concrete Scale Horizon
|
|
15
|
+
- Assume 10,000,000 active concurrent user sessions.
|
|
16
|
+
- If 1% make an API request in any given second, arrival rate $\lambda = 100,000\text{ req/sec}$.
|
|
17
|
+
- **Scenario A (Healthy Latency):** Average latency $W = 50\text{ ms } (0.05\text{ s})$.
|
|
18
|
+
$$L = 100,000 \times 0.05 = 5,000\text{ concurrent in-flight requests}$$
|
|
19
|
+
- **Scenario B (Degraded Latency / Hot Key Lock):** A single unindexed query or row lock slips average latency to $W = 500\text{ ms } (0.5\text{ s})$.
|
|
20
|
+
$$L = 100,000 \times 0.5 = 50,000\text{ concurrent in-flight requests}$$
|
|
21
|
+
- **Result:** A 10x latency regression triggers a 10x surge in in-flight requests. Thread pools, database connection pools, file descriptors, and socket buffers saturate immediately, triggering cascading system brownout.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 2. Hot-Key Defense & Contention Elimination
|
|
26
|
+
|
|
27
|
+
In high-concurrency systems, synchronous row updates on a single entity (e.g. `UPDATE products SET inventory = inventory - 1`, or `UPDATE metrics SET views = views + 1`) introduce devastating lock contention.
|
|
28
|
+
|
|
29
|
+
### Strategy A: Sharded Counters
|
|
30
|
+
Divide a monolithic counter row into $N$ distinct shards (e.g., 16 or 64 shards):
|
|
31
|
+
- **Write Path:** The writer randomly selects shard index $i \in [0, N-1]$ and increments shard $i$. Contention drops by a factor of $N$.
|
|
32
|
+
- **Read Path:** Compute the sum across all $N$ shards using a single query:
|
|
33
|
+
```sql
|
|
34
|
+
SELECT COALESCE(SUM(count), 0) FROM metric_shards WHERE metric_id = :id;
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Strategy B: Append-Only Event Ledgers
|
|
38
|
+
Never update an account balance or inventory count in place synchronously:
|
|
39
|
+
1. Append an immutable transaction record into an append-only ledger (`ledger_entries`).
|
|
40
|
+
2. Materialize balances periodically or asynchronously via event streaming / stream processors.
|
|
41
|
+
3. For immediate balance checks, query `SELECT COALESCE(SUM(delta), 0) FROM ledger_entries WHERE account_id = :id`.
|
|
42
|
+
|
|
43
|
+
### Strategy C: Asynchronous Batch Rollups
|
|
44
|
+
For high-frequency, non-transactional metrics (views, likes, heartbeats):
|
|
45
|
+
1. Buffer mutations in high-throughput in-memory or Redis hyperloglogs / queues.
|
|
46
|
+
2. Flush to persistent storage in micro-batches (e.g., every 500ms or 1,000 items) using bulk operations (`INSERT ... ON CONFLICT DO UPDATE`).
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## 3. Keyset (Cursor) Pagination vs Offset Degradation
|
|
51
|
+
|
|
52
|
+
Offset pagination (`LIMIT 100 OFFSET 1000000`) forces the database engine to perform a full scan over 1,000,100 index entries or rows, discarding the first million. Under high concurrency, this locks buffer pools and consumes gigabytes of I/O.
|
|
53
|
+
|
|
54
|
+
### Mandatory Cursor Keyset Invariant
|
|
55
|
+
Use deterministic composite cursor ordering:
|
|
56
|
+
```sql
|
|
57
|
+
SELECT id, title, created_at
|
|
58
|
+
FROM articles
|
|
59
|
+
WHERE (created_at, id) < (:last_created_at, :last_id)
|
|
60
|
+
ORDER BY created_at DESC, id DESC
|
|
61
|
+
LIMIT 100;
|
|
62
|
+
```
|
|
63
|
+
Required composite index:
|
|
64
|
+
```sql
|
|
65
|
+
CREATE INDEX idx_articles_created_at_id ON articles (created_at DESC, id DESC);
|
|
66
|
+
```
|
|
67
|
+
- Seek time remains $O(\log N)$ regardless of how deep the user paginates.
|
|
68
|
+
- Hard bound: Every read query must specify a maximum limit (default: 50, max: 100).
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 4. Bounded Concurrency & Pool Management
|
|
73
|
+
|
|
74
|
+
Unbounded parallel operations will rapidly exhaust Node.js/Go/Rust file descriptors, thread pools, and downstream database connections.
|
|
75
|
+
|
|
76
|
+
### Prohibited
|
|
77
|
+
```typescript
|
|
78
|
+
// FATAL DEFECT: If items has 10,000 elements, creates 10,000 simultaneous sockets/queries
|
|
79
|
+
await Promise.all(items.map(item => processItem(item)));
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Mandatory Bounded Concurrency
|
|
83
|
+
Use a semaphore or bounded concurrency queue (e.g. limit concurrency to 10-25 workers):
|
|
84
|
+
```typescript
|
|
85
|
+
async function mapConcurrent<T, R>(
|
|
86
|
+
items: readonly T[],
|
|
87
|
+
limit: number,
|
|
88
|
+
fn: (item: T, signal: AbortSignal) => Promise<R>,
|
|
89
|
+
signal: AbortSignal
|
|
90
|
+
): Promise<R[]> {
|
|
91
|
+
const results: R[] = new Array(items.length);
|
|
92
|
+
let nextIndex = 0;
|
|
93
|
+
|
|
94
|
+
async function worker(): Promise<void> {
|
|
95
|
+
while (nextIndex < items.length) {
|
|
96
|
+
if (signal.aborted) throw signal.reason;
|
|
97
|
+
const index = nextIndex++;
|
|
98
|
+
results[index] = await fn(items[index]!, signal);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const pool = Array.from({ length: Math.min(limit, items.length) }, () => worker());
|
|
103
|
+
await Promise.all(pool);
|
|
104
|
+
return results;
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## 5. Exponential Backoff with Full Jitter
|
|
111
|
+
|
|
112
|
+
When a downstream service degrades or drops connections, naive retries or flat sleep intervals create a **thundering herd** that ensures the downstream service can never recover.
|
|
113
|
+
|
|
114
|
+
### The Full Jitter Algorithm
|
|
115
|
+
For retry attempt $i \ge 0$, calculate delay $T_i$:
|
|
116
|
+
$$T_{\text{temp}} = \min(T_{\max}, T_{\text{base}} \times 2^i)$$
|
|
117
|
+
$$T_i = \text{random}(0, T_{\text{temp}})$$
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
function calculateJitteredBackoff(
|
|
121
|
+
attempt: number,
|
|
122
|
+
baseMs = 100,
|
|
123
|
+
maxMs = 5000
|
|
124
|
+
): number {
|
|
125
|
+
const expCap = Math.min(maxMs, baseMs * (2 ** attempt));
|
|
126
|
+
return Math.floor(Math.random() * expCap);
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
## 6. Timeouts & Cancellation
|
|
133
|
+
|
|
134
|
+
Every external interaction (HTTP request, database query, cache call, inter-process call) must be bounded by a non-negotiable timeout.
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
// Modern native timeout using AbortSignal.timeout
|
|
138
|
+
async function safeFetch(url: string, init?: RequestInit, timeoutMs = 3000): Promise<Response> {
|
|
139
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
140
|
+
const combinedSignal = init?.signal
|
|
141
|
+
? AbortSignal.any([init.signal, timeoutSignal])
|
|
142
|
+
: timeoutSignal;
|
|
143
|
+
|
|
144
|
+
return fetch(url, { ...init, signal: combinedSignal });
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## 7. Idempotency & Transaction Discipline
|
|
151
|
+
|
|
152
|
+
### The Idempotency Key Pattern
|
|
153
|
+
1. Client generates a deterministic or UUID `Idempotency-Key` header on state mutations.
|
|
154
|
+
2. Server stores the request key in an atomic fast-path cache (e.g. Redis `SET key ... NX EX 86400`) with status `IN_PROGRESS`.
|
|
155
|
+
3. If duplicate key arrives while `IN_PROGRESS`, return `409 Conflict` or poll/await completion.
|
|
156
|
+
4. When mutation completes, update cache with the serialized response. Re-deliver cached response on subsequent retries.
|
|
157
|
+
|
|
158
|
+
### Transaction Seam Discipline
|
|
159
|
+
**Never hold a database transaction open across network calls.**
|
|
160
|
+
```
|
|
161
|
+
BAD:
|
|
162
|
+
BEGIN TRANSACTION
|
|
163
|
+
UPDATE accounts SET balance = balance - 100
|
|
164
|
+
await fetch("https://payment-gateway/charge") // NETWORK CALL INSIDE TRANSACTION!
|
|
165
|
+
UPDATE payments SET status = 'COMPLETED'
|
|
166
|
+
COMMIT
|
|
167
|
+
|
|
168
|
+
GOOD:
|
|
169
|
+
1. Reserve funds via Optimistic Concurrency or state = 'PENDING' in short local transaction.
|
|
170
|
+
2. COMMIT local transaction.
|
|
171
|
+
3. Perform external HTTP call with explicit timeout and idempotency key.
|
|
172
|
+
4. Update state to 'CONFIRMED' in a second short local transaction.
|
|
173
|
+
```
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Paranoid Threat & Scale Record Contract
|
|
2
|
+
|
|
3
|
+
When evaluating high-concurrency systems, critical endpoints, or architectural designs, save the evaluation as a persistent JSON record (`paranoid-record.json`) to establish verifiable compliance before implementation.
|
|
4
|
+
|
|
5
|
+
## Schema Specification (`schema_version: "1.0"`)
|
|
6
|
+
|
|
7
|
+
```json
|
|
8
|
+
{
|
|
9
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
10
|
+
"title": "ParanoidArchitectureRecord",
|
|
11
|
+
"type": "object",
|
|
12
|
+
"required": [
|
|
13
|
+
"schema_version",
|
|
14
|
+
"goal",
|
|
15
|
+
"scale_profile",
|
|
16
|
+
"threat_pre_mortem",
|
|
17
|
+
"trust_boundaries",
|
|
18
|
+
"concurrency_controls",
|
|
19
|
+
"bounded_limits",
|
|
20
|
+
"verdict"
|
|
21
|
+
],
|
|
22
|
+
"properties": {
|
|
23
|
+
"schema_version": { "type": "string", "const": "1.0" },
|
|
24
|
+
"goal": { "type": "string", "minLength": 10 },
|
|
25
|
+
"scale_profile": {
|
|
26
|
+
"type": "object",
|
|
27
|
+
"required": ["target_concurrency", "throughput_rps", "latency_budget_ms"],
|
|
28
|
+
"properties": {
|
|
29
|
+
"target_concurrency": { "type": "integer", "minimum": 10000000 },
|
|
30
|
+
"throughput_rps": { "type": "integer", "minimum": 1000 },
|
|
31
|
+
"latency_budget_ms": { "type": "integer", "maximum": 500 }
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"threat_pre_mortem": {
|
|
35
|
+
"type": "array",
|
|
36
|
+
"minItems": 3,
|
|
37
|
+
"items": {
|
|
38
|
+
"type": "object",
|
|
39
|
+
"required": ["id", "threat_class", "description", "mitigation"],
|
|
40
|
+
"properties": {
|
|
41
|
+
"id": { "type": "string" },
|
|
42
|
+
"threat_class": {
|
|
43
|
+
"type": "string",
|
|
44
|
+
"enum": [
|
|
45
|
+
"race_condition",
|
|
46
|
+
"hot_key_contention",
|
|
47
|
+
"unbounded_concurrency",
|
|
48
|
+
"injection",
|
|
49
|
+
"timing_attack",
|
|
50
|
+
"edos",
|
|
51
|
+
"toctou",
|
|
52
|
+
"memory_leak",
|
|
53
|
+
"network_stall"
|
|
54
|
+
]
|
|
55
|
+
},
|
|
56
|
+
"description": { "type": "string", "minLength": 15 },
|
|
57
|
+
"mitigation": { "type": "string", "minLength": 15 }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"trust_boundaries": {
|
|
62
|
+
"type": "array",
|
|
63
|
+
"minItems": 1,
|
|
64
|
+
"items": {
|
|
65
|
+
"type": "object",
|
|
66
|
+
"required": ["name", "schema_validation", "data_layer_ownership"],
|
|
67
|
+
"properties": {
|
|
68
|
+
"name": { "type": "string" },
|
|
69
|
+
"schema_validation": { "type": "string" },
|
|
70
|
+
"data_layer_ownership": { "type": "string" }
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
"concurrency_controls": {
|
|
75
|
+
"type": "object",
|
|
76
|
+
"required": ["idempotency", "locking_strategy"],
|
|
77
|
+
"properties": {
|
|
78
|
+
"idempotency": {
|
|
79
|
+
"type": "object",
|
|
80
|
+
"required": ["enabled", "key_header", "storage"],
|
|
81
|
+
"properties": {
|
|
82
|
+
"enabled": { "type": "boolean" },
|
|
83
|
+
"key_header": { "type": "string" },
|
|
84
|
+
"storage": { "type": "string" }
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
"locking_strategy": {
|
|
88
|
+
"type": "string",
|
|
89
|
+
"enum": ["optimistic_occ", "sharded_counters", "event_ledger", "partitioned_lock"]
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
"bounded_limits": {
|
|
94
|
+
"type": "object",
|
|
95
|
+
"required": ["max_read_limit", "max_payload_bytes", "network_timeout_ms", "backoff_algorithm"],
|
|
96
|
+
"properties": {
|
|
97
|
+
"max_read_limit": { "type": "integer", "maximum": 100 },
|
|
98
|
+
"max_payload_bytes": { "type": "integer", "maximum": 10485760 },
|
|
99
|
+
"network_timeout_ms": { "type": "integer", "maximum": 10000 },
|
|
100
|
+
"backoff_algorithm": { "type": "string", "const": "exponential_full_jitter" }
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
"verdict": {
|
|
104
|
+
"type": "object",
|
|
105
|
+
"required": ["action", "rationale", "revisit_triggers"],
|
|
106
|
+
"properties": {
|
|
107
|
+
"action": { "type": "string", "enum": ["proceed", "pause", "refuse"] },
|
|
108
|
+
"rationale": { "type": "string", "minLength": 20 },
|
|
109
|
+
"revisit_triggers": {
|
|
110
|
+
"type": "array",
|
|
111
|
+
"minItems": 1,
|
|
112
|
+
"items": { "type": "string" }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Audit Tooling
|
|
121
|
+
|
|
122
|
+
Validate records against this contract using:
|
|
123
|
+
```bash
|
|
124
|
+
python3 scripts/paranoid_guard.py audit <record.json> --json
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Exit codes:
|
|
128
|
+
- `0`: Structurally compliant record.
|
|
129
|
+
- `1`: JSON parsing or file access failure.
|
|
130
|
+
- `2`: Validation findings (missing threats, unbounded limits, or unmitigated risks).
|