Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 42 additions & 33 deletions docs/PERFORMANCE_TUNING.md
Original file line number Diff line number Diff line change
@@ -1,49 +1,58 @@
# Performance Tuning Guide
# Performance Tuning

This guide details optimization strategies, configuration techniques, operational tradeoffs, and empirical benchmark measurements for high-throughput, low-latency deployments using the StellarSplit SDK.
This guide covers tuning knobs that affect SDK throughput and latency.

---
## Resource Pooling

## Table of Contents

1. [Overview & Architecture Considerations](#1-overview--architecture-considerations)
2. [Technique 1: RPC Connection Pooling](#technique-1-rpc-connection-pooling)
3. [Technique 2: RPC Request Multiplexing & Batching](#technique-2-rpc-request-multiplexing--batching)
4. [Technique 3: Multi-Tier Caching & Optimistic Reads](#technique-3-multi-tier-caching--optimistic-reads)
5. [Technique 4: Circuit Breaking & Adaptive Throttling](#technique-4-circuit-breaking--adaptive-throttling)
6. [Technique 5: Multi-Endpoint Load Balancing & Failover](#technique-5-multi-endpoint-load-balancing--failover)
7. [Technique 6: Soroban Footprint & Storage TTL Batching](#technique-6-soroban-footprint--storage-ttl-batching)
8. [Technique 7: Real-Time Event Streaming vs. Polling](#technique-7-real-time-event-streaming-vs-polling)
9. [Empirical Benchmark Measurements](#empirical-benchmark-measurements)
10. [Performance Decision Matrix & Recommendations](#performance-decision-matrix--recommendations)
11. [Profiling Guide](#profiling-guide)
12. [Optimization Checklist](#optimization-checklist)
The SDK reuses expensive resources (connections, buffers, clients) through a
pool subsystem. Pooling maximizes reuse by handing out idle resources before
creating new ones, and by returning resources to the pool on release.

---
### Pool lifecycle

## 1. Overview & Architecture Considerations
Each pooled resource moves through a well-defined lifecycle:

In Stellar-based decentralized invoice applications, performance bottlenecks typically arise from four distinct layers:
1. **Create** — the pool calls the configured factory to build a new resource
when no idle resource is available and the pool is below its maximum size.
2. **Validate** — before an idle resource is reused, the optional validator is
invoked. Resources that fail validation are destroyed and replaced.
3. **Acquire / Release** — callers acquire a resource, use it, then release it
back to the pool. Released resources become idle and eligible for reuse.
4. **Destroy** — resources are destroyed when they fail validation, exceed the
idle timeout, or when the pool is drained.
5. **Drain / Close** — draining stops new acquisitions and destroys all idle
resources; closing additionally waits for in-use resources to be released.

1. **Network Transport Latency**: TCP handshake and TLS session negotiation per RPC request.
2. **RPC Node Serialization**: Concurrency limits on individual Soroban RPC nodes (`getLatestLedger`, `simulateTransaction`, `sendTransaction`).
3. **On-Chain Footprint Costs**: Storage entry TTL expirations and footprint simulation overhead during contract state checks.
4. **Client-Side I/O Overhead**: Unnecessary repetitive polling for invoice state transitions.
### Sizing

The StellarSplit SDK includes built-in subsystems to mitigate each bottleneck. The sections below describe how to tune these features.
Pool size is configurable per pool:

---
| Option | Description |
| ----------------- | ------------------------------------------------------------------ |
| `min` | Minimum number of resources kept warm in the pool. |
| `max` | Maximum number of resources (idle + in-use) the pool will create. |
| `idleTimeout` | How long an idle resource may sit before it is destroyed. |
| `acquireTimeout` | How long an acquire call waits for a resource before failing. |

## Technique 1: RPC Connection Pooling
Guidance:

### Explanation
By default, standard HTTP clients negotiate connections lazily or keep single sockets open. Under high concurrency (e.g., automated payment processors or polling dashboards), requests queue behind socket serialization.
- Set `min` to the steady-state concurrency you expect so common requests are
served from warm resources without a create/validate round trip.
- Set `max` to a value your downstream dependency can tolerate; the pool will
never exceed it, and acquires beyond it wait up to `acquireTimeout`.
- Keep `idleTimeout` short enough to shed resources during quiet periods, but
long enough to avoid churn during bursty traffic.
- Tune `acquireTimeout` so callers fail fast instead of queueing indefinitely
when the pool is saturated.

The SDK provides an integrated connection pool (`ConnectionPool`) that maintains a warm pool of keep-alive sockets for Soroban RPC calls.
### Tracking

### Code Example
```typescript
import { StellarSplitClient } from "@stellar-split/sdk";
Pools expose counters for observability: total created, currently idle,
currently in-use, waiting acquirers, and destroyed. Use these to confirm reuse
is high (few creates relative to acquires) and to spot saturation (growing
waiting count) before it becomes a latency problem.

### Tuning checklist

const client = new StellarSplitClient({
rpcUrl: "https://soroban-rpc.mainnet.stellar.org",
Expand Down
80 changes: 79 additions & 1 deletion docs/SDK_TUTORIALS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ This guide provides step-by-step tutorials for integrating with the StellarSplit
4. [Webhook Integration](#webhook-integration)
5. [Multi-Signature Wallets](#multi-signature-wallets)
6. [Error Handling](#error-handling)
7. [Production Checklist](#production-checklist)
7. [CLI Tools](#cli-tools)
8. [Production Checklist](#production-checklist)

---

Expand Down Expand Up @@ -209,6 +210,83 @@ try {

---

## CLI Tools

The SDK ships a `stellarsplit` command-line tool for scripting and automation.

### Global Help

```bash
stellarsplit --help
stellarsplit <command> --help
```

### Commands

| Command | Description |
|---------|-------------|
| `invoice create` | Create a new invoice |
| `invoice get <id>` | Fetch an invoice by ID |
| `pay` | Pay toward an invoice |
| `config` | Show or set CLI configuration |

### Configuration

```bash
stellarsplit config set rpcUrl https://soroban-testnet.stellar.org
stellarsplit config set contractId YOUR_DEPLOYED_CONTRACT_ID
stellarsplit config show
```

### Create an Invoice

```bash
stellarsplit invoice create \
--creator GABC...CREATOR \
--recipient GABC...RECIPIENT1:60 \
--recipient GDEF...RECIPIENT2:40 \
--token USDC_CONTRACT_ADDRESS \
--deadline-days 7
```

### Fetch an Invoice

```bash
stellarsplit invoice get 42
```

### Pay Toward an Invoice

```bash
stellarsplit pay --payer GABC...PAYER --invoice 42 --amount 25
```

### Scripting Support

All commands are non-interactive and support machine-readable output:

```bash
# Emit JSON for parsing in scripts
stellarsplit invoice get 42 --json

# Suppress non-essential output
stellarsplit pay --payer GABC... --invoice 42 --amount 25 --quiet

# Capture the transaction hash
TX_HASH=$(stellarsplit pay --payer GABC... --invoice 42 --amount 25 --json | jq -r '.txHash')
```

### Exit Codes

| Code | Meaning |
|------|---------|
| `0` | Success |
| `1` | General error |
| `2` | Invalid usage / bad arguments |
| `3` | SDK operation failed (e.g. invoice not found) |

---

## Production Checklist

Before deploying to production:
Expand Down
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@
"types": "./dist/lazy/index.d.ts",
"import": "./dist/lazy/index.js",
"require": "./dist/lazy/index.cjs"
},
"./security": {
"types": "./dist/security/index.d.ts",
"import": "./dist/security/index.js",
"require": "./dist/security/index.cjs"
}
},
"files": [
Expand Down Expand Up @@ -75,7 +80,8 @@
"docs": "typedoc",
"size-audit": "tsx scripts/bundle-size-audit.ts",
"bundle:check": "tsx scripts/bundle-size-guard.ts",
"bundle:update-baseline": "BUNDLE_BASELINE_UPDATE=true tsx scripts/bundle-size-guard.ts"
"bundle:update-baseline": "BUNDLE_BASELINE_UPDATE=true tsx scripts/bundle-size-guard.ts",
"cli": "tsx src/cli/index.ts"
},
"bin": {
"stellar-split-sdk-migrate": "./dist/cli/migrate.js",
Expand Down
127 changes: 127 additions & 0 deletions src/__tests__/logging.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ import {
createLogger,
type LogEntry,
} from '../logging';
import {
AuditLogger,
AuditAction,
AuditSeverity,
InMemoryAuditStore,
createAuditLogger,
type AuditRecord,
} from '../audit';
import {
sanitizeHtml,
encodeHtml,
sanitizeValue,
XssProtectionTracker,
} from '../xss';

describe('logging system', () => {
let aggregator: LogAggregator;
Expand Down Expand Up @@ -98,3 +112,116 @@ describe('logging system', () => {
]);
});
});

describe('audit logging', () => {
let store: InMemoryAuditStore;

beforeEach(() => {
store = new InMemoryAuditStore();
});

it('emits structured audit records with actor, action, severity and timestamp', () => {
const audit = createAuditLogger({ store });
audit.record({
action: AuditAction.Login,
severity: AuditSeverity.Info,
actor: 'user-1',
resource: 'session',
metadata: { ip: '127.0.0.1' },
});

const records = store.query();
expect(records).toHaveLength(1);
const record = records[0] as AuditRecord;
expect(record.action).toBe(AuditAction.Login);
expect(record.severity).toBe(AuditSeverity.Info);
expect(record.actor).toBe('user-1');
expect(record.resource).toBe('session');
expect(record.metadata).toEqual({ ip: '127.0.0.1' });
expect(typeof record.id).toBe('string');
expect(typeof record.timestamp).toBe('string');
expect(Number.isNaN(Date.parse(record.timestamp))).toBe(false);
});

it('persists records reliably in the store', () => {
const audit = new AuditLogger({ store });
audit.record({ action: AuditAction.Create, severity: AuditSeverity.Info, actor: 'a' });
audit.record({ action: AuditAction.Update, severity: AuditSeverity.Warn, actor: 'b' });
audit.record({ action: AuditAction.Delete, severity: AuditSeverity.Critical, actor: 'c' });

expect(store.size()).toBe(3);
expect(store.query()).toHaveLength(3);
});

it('supports efficient queries by action, severity, actor and time range', () => {
const audit = createAuditLogger({ store });
audit.record({ action: AuditAction.Login, severity: AuditSeverity.Info, actor: 'u1' });
audit.record({ action: AuditAction.Logout, severity: AuditSeverity.Info, actor: 'u1' });
audit.record({ action: AuditAction.Delete, severity: AuditSeverity.Critical, actor: 'u2' });

expect(store.query({ action: AuditAction.Login })).toHaveLength(1);
expect(store.query({ severity: AuditSeverity.Critical })).toHaveLength(1);
expect(store.query({ actor: 'u1' })).toHaveLength(2);

const all = store.query();
const from = all[0].timestamp;
expect(store.query({ from })).toHaveLength(3);
});

it('tracks audits with analytics over persisted records', () => {
const audit = createAuditLogger({ store });
audit.record({ action: AuditAction.Login, severity: AuditSeverity.Info, actor: 'u1' });
audit.record({ action: AuditAction.Login, severity: AuditSeverity.Info, actor: 'u2' });
audit.record({ action: AuditAction.Delete, severity: AuditSeverity.Critical, actor: 'u1' });

const analytics = store.analytics();
expect(analytics.total).toBe(3);
expect(analytics.byAction[AuditAction.Login]).toBe(2);
expect(analytics.bySeverity[AuditSeverity.Critical]).toBe(1);
expect(analytics.byActor['u1']).toBe(2);
});

it('clears persisted audit records', () => {
const audit = createAuditLogger({ store });
audit.record({ action: AuditAction.Login, severity: AuditSeverity.Info, actor: 'u1' });
store.clear();
expect(store.query()).toHaveLength(0);
expect(store.size()).toBe(0);
});
});

describe('xss protection', () => {
it('encodes all HTML special characters', () => {
expect(encodeHtml('&<>"\'/`=')).toBe(
'&amp;&lt;&gt;&quot;&#39;&#47;&#96;&#61;',
);
});

it('sanitizes script and event handler payloads', () => {
expect(sanitizeHtml('<script>alert(1)</script>')).not.toContain('<script>');
expect(sanitizeHtml('<img src=x onerror=alert(1)>')).not.toContain('onerror');
expect(sanitizeHtml('<a href="javascript:alert(1)">x</a>')).not.toContain('javascript:');
});

it('sanitizes nested objects and arrays', () => {
const input = {
name: '<b>bold</b>',
nested: { html: '<script>x</script>', list: ['<i>a</i>', { deep: '<u>b</u>' }] },
};
const output = sanitizeValue(input) as typeof input;
expect(output.name).not.toContain('<b>');
expect(output.nested.html).not.toContain('<script>');
expect(output.nested.list[0]).not.toContain('<i>');
expect((output.nested.list[1] as { deep: string }).deep).not.toContain('<u>');
});

it('tracks applied protections', () => {
const tracker = new XssProtectionTracker();
tracker.record('sanitize', '<script>');
tracker.record('encode', '&');
expect(tracker.count()).toBe(2);
expect(tracker.getEvents()).toHaveLength(2);
tracker.clear();
expect(tracker.count()).toBe(0);
});
});
Loading