Glossary
Web Developer Dictionary
Визначення технічних термінів з PHP, DevOps, MySQL та AI — з прикладами коду та поясненнями простою мовою.
228
terms
27
letters
S
Saga Pattern
Saga is a pattern for managing distributed transactions without 2PC. A long business transaction is broken into a sequence of local transactions. Each local transaction publishes an event or message. On failure, compensating transactions are executed.
Two types
Choreography — each service reacts to events and publishes the next ones. No central coordinator. Simple, but the flow is hard to trace
Orchestration — a central Saga Orchestrator coordinates services by sending commands and processing results. More complex, but more transparent
Example: order placement
CreateOrder → ReserveInventory → ProcessPayment → ShipOrder
if ProcessPayment fails:
→ ReleaseInventory (compensating)
→ CancelOrder (compensating)
Challenges
Compensating transactions are not always possible (a sent message cannot be unsent). Saga provides Eventual Consistency, not ACID. Debugging is harder than with a regular transaction.
Security Headers
Security headers are HTTP response headers that instruct the browser to apply additional security measures. Free protection with a single line of server configuration.
Important headers
Strict-Transport-Security: max-age=31536000; includeSubDomains — always HTTPS, even if the user typed http://
Content-Security-Policy — which sources to trust for scripts, styles, images. Protects against XSS
X-Frame-Options: DENY — block embedding in iframes. Protects against clickjacking
X-Content-Type-Options: nosniff — browser does not sniff content type
Referrer-Policy: strict-origin-when-cross-origin — controls the Referer header
Permissions-Policy — restrict access to browser APIs (camera, mic, geolocation)
Checking
securityheaders.com — free scanner with A-F grading. Mozilla Observatory — additional audit.
Semantic Versioning (SemVer)
Semantic versioning is a version-numbering convention in the format MAJOR.MINOR.PATCH (2.4.1). Each part carries specific meaning, so a developer immediately understands whether an upgrade is safe.RulesPATCH (2.4.1 → 2.4.2) — bug fixes. Backwards-compatible; upgrade freelyMINOR (2.4.1 → 2.5.0) — new features. Backwards-compatible; old code keeps workingMAJOR (2.4.1 → 3.0.0) — breaking changes. Review before upgradingIn Composer and npm"^2.4.1" — allows MINOR and PATCH (2.x.x), but not MAJOR"~2.4.1" — allows PATCH only (2.4.x)"2.4.1" — pinned versionPre-release and metadata2.0.0-alpha.1, 2.0.0-rc.2 — pre-release versions. 2.0.0+build.42 — build metadata (does not affect comparisons).
Server-Sent Events (SSE)
SSE (Server-Sent Events) is a standard browser API for receiving a stream of updates from the server over a regular HTTP connection. Unidirectional: server → client only. Simpler than WebSocket when two-way communication is not needed.
How it works
The client opens a connection via EventSource. The server responds with Content-Type: text/event-stream and keeps the connection open, sending events in the format:
data: {"price": 42.5, "symbol": "BTC"}\n\n
Client-side code
const es = new EventSource('/api/prices');
es.onmessage = (e) => {
const data = JSON.parse(e.data);
updatePrice(data.symbol, data.price);
};
es.onerror = () => es.close();
SSE vs WebSocket
SSE — simpler, HTTP/2-friendly, automatic reconnection, text-only
WebSocket — bidirectional, binary data, more complex
SSE is ideal for live dashboards, notification streaming, prices, and task progress.
Serverless
Serverless is a deployment model where you write a function (handler) and pay only for the time it runs. Servers exist, but you do not think about them: the provider scales automatically from zero to billions of invocations.How it worksYou upload code. When an HTTP request or event (S3 upload, queue message) arrives, the provider spins up a container with your function, executes it, and shuts it down. A "cold start" — the first invocation after idle time — can add latency (tens of ms to seconds).When it fitsIrregular load: from zero to peak trafficEvent-driven tasks: file processing, webhooks, DB triggersMVPs and prototypes — no server setup neededWhen it does not fitLong-running processes (15-min execution limit in AWS Lambda)Steady traffic — more expensive than a traditional serverStateful applications with persistent connections (WebSocket)
Service Mesh
A service mesh is an infrastructure layer that manages network communication between microservices: traffic, security (mTLS), observability, circuit breaking — without changing application code. Implemented via sidecar proxies (usually Envoy).
What it provides
Traffic management — canary deployments, A/B testing, retries, timeouts, inter-service rate limiting
Security — automatic mTLS between all services. Zero Trust at the network level
Observability — automatic latency, error rate, and tracing metrics between services with no code changes
Circuit Breaking — protection from cascading failures at the proxy level
How it works
A sidecar container (Envoy) runs alongside each Pod. All inbound and outbound traffic passes through it. The control plane (Istiod) configures all proxies centrally.
Popular solutions
Istio (most popular), Linkerd (simpler), Consul Connect.
Service Worker
A Service Worker is a JavaScript file that runs in a background browser thread, independently of the page. It intercepts network requests, caches resources, and enables offline operation. The technical foundation of PWAs.
How it is registered
// Registration
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
// sw.js — the Service Worker file
self.addEventListener('install', event => {
event.waitUntil(
caches.open('v1').then(cache =>
cache.addAll(['/index.html', '/app.css', '/app.js'])
)
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cached =>
cached ?? fetch(event.request)
)
);
});
Caching strategies
Cache First — use cache if available; network as fallback. For static assets
Network First — try network; fall back to cache if unavailable. For APIs
Stale While Revalidate — return cache immediately, update in background
Limitations
HTTPS only. No direct DOM access. Its own lifecycle (install → activate → fetch).
Session
A session is a mechanism for persisting state between HTTP requests on the server side. The server stores session data (user_id, cart, flash messages) while the client receives only a session identifier — typically in a cookie.How it worksOn the first request, the server creates a session_id, stores the session data, and sends the session_id in a cookie. Every subsequent request contains that cookie — the server finds the data and "recognises" the user.Where data is storedFilesystem — simple, but does not scale across multiple serversDatabase — centralised, but adds latency to every requestRedis / Memcached — the most common production choice. Fast and scalableSession vs JWTA session is server-side state; JWT is client-side state (in the token). A session can be invalidated instantly; a JWT can only expire naturally or via a blacklist. Sessions suit traditional web apps; JWT suits stateless APIs and microservices.
Sharding
Sharding is horizontal database scaling: data is split into partitions (shards) distributed across separate servers. A single server cannot handle billions of rows — sharding distributes the load.Partitioning strategiesRange-based — shard 1: id 1–1M, shard 2: id 1M–2M. Simple, but uneven loadHash-based — shard = hash(id) % N. Even distribution, but painful reshardingDirectory-based — a separate catalogue service knows where each record lives. Flexible, but an extra hopChallengesJOINs across shards are impossible or very expensiveTransactions spanning multiple shards require distributed transaction protocols (2PC)Resharding when adding a new server is a painful operation
Short-Circuit Evaluation
Short-circuit evaluation is an optimisation of logical expression evaluation: if the result is already known after the first operand, the second is not evaluated. Common behaviour in all programming languages.
Rules
A && B — if A is false, B is not evaluated (result is already false)
A || B — if A is true, B is not evaluated (result is already true)
Practical uses
// Safe check before access
if ($user && $user->isAdmin()) { ... }
// Default value — if first is falsy, return second
$name = $input['name'] ?? 'Guest';
// Conditional execution
$debug && error_log($message);
// Guard clause — stop the chain
$result = getData() || throw new NotFoundException();
Side effects
If the second operand has a side effect (DB query, log write) — it will not execute on short-circuit. Keep this in mind when designing conditions.
Singleton
Singleton is a design pattern that guarantees only one instance of a class exists and provides a global access point to it. Classic uses: a configuration class, logger, or DB connection.Implementationclass Config {
private static ?self $instance = null;
private function __construct() {}
public static function getInstance(): self {
self::$instance ??= new self();
return self::$instance;
}
}CriticismSingleton is one of the most criticised patterns. It introduces global state, complicates testing (hard to replace with a mock), and violates Dependency Inversion. In modern code it is replaced by registering the dependency as a singleton in an IoC container.
SLI, SLO, SLA
Three concepts from SRE (Site Reliability Engineering) practice for measuring and agreeing on service reliability between teams and customers.
SLI — Service Level Indicator
A numeric metric describing service health. Examples: percentage of successful requests, p99 latency, uptime. "What we measure"
SLO — Service Level Objective
An internal target for an SLI. "The bar we set for ourselves". Example: 99.9% of requests completed in < 500 ms. The SLO is stricter than the SLA — a "buffer" for the team.
SLA — Service Level Agreement
A legal contract with the customer. "What we promise externally". Violating the SLA triggers financial penalties. Hence the SLA is always softer than the SLO.
Error Budget
SLO 99.9% = 0.1% of allowed errors per month ≈ 43 minutes of downtime. The error budget shows how much "reliability balance" remains. If the budget is exhausted — new deploys stop.
Soft Delete
Soft delete is a "soft" deletion pattern: a record is not physically removed from the database but is marked as deleted via a deleted_at field (timestamp). All queries automatically filter out "deleted" records.
Why use it
Recovering accidentally deleted data
Audit and compliance: data is retained as required by law
Preserving references: if an Order references a deleted User, the record stays
Implementation
-- Migration: add the field
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
-- "Delete"
UPDATE users SET deleted_at = NOW() WHERE id = 42;
-- Queries ignore "deleted" records
SELECT * FROM users WHERE deleted_at IS NULL;
Downsides
The table grows and is never cleaned — archiving is needed
Unique constraints: a deleted email may block a new account
More complex JOINs and queries
SOLID
SOLID is five object-oriented design principles formulated by Robert Martin. Together they describe how to write code that is easy to read, test, and change.Five principlesS — Single Responsibility — a class should have only one reason to change. A UserService should not simultaneously send emails and write to the databaseO — Open/Closed — open for extension, closed for modification. Add new behaviour through new classes, not by changing existing onesL — Liskov Substitution — a subclass must be substitutable for its parent without altering the program's behaviourI — Interface Segregation — prefer several narrow interfaces over one wide one. A client should not depend on methods it does not useD — Dependency Inversion — depend on abstractions, not on concrete implementations
SPA (Single Page Application)
SPA (Single Page Application) is an application where the browser loads a single HTML page, and all subsequent navigation happens without a full reload: JavaScript dynamically updates the DOM and fetches data via an API.AdvantagesSmooth navigation without page flickerUI logic in JavaScript — the server returns only data (JSON API)Can be enhanced into a PWA (Progressive Web App)DisadvantagesSEO — search bots handle JavaScript-rendered content poorly. Solved with SSR or Static GenerationInitial load — a large JS bundle can take time to parse on low-end devicesMore complex development — state management, routing, auth — all in JSPopular frameworksReact, Vue, Angular, Svelte. Often combined with meta-frameworks (Next.js, Nuxt, SvelteKit) that add SSR and Static Generation.
Spread Operator (...)
The spread operator (...) in PHP unpacks an array or Traversable into a list of arguments or elements. It simplifies passing a variable number of arguments and merging arrays.
Unpacking into arguments
function sum(int ...$nums): int {
return array_sum($nums);
}
$numbers = [1, 2, 3];
echo sum(...$numbers); // 6
Variadic functions
function log(string $level, string ...$messages): void {
foreach ($messages as $msg) {
echo "[$level] $msg\n";
}
}
log('info', 'Started', 'Connected', 'Done');
Merging arrays (PHP 8.1 — string keys)
$defaults = ['color' => 'blue', 'size' => 'M'];
$custom = ['color' => 'red'];
$result = [...$defaults, ...$custom];
// ['color' => 'red', 'size' => 'M']
SQL Injection
SQL Injection is an attack where a malicious actor inserts arbitrary SQL code into a query through user input. If the application concatenates it without escaping, the attacker can read any data, modify or delete it, and in some databases execute OS commands.Classic exampleThe query SELECT * FROM users WHERE email = '{$email}' with input ' OR 1=1 -- becomes WHERE email = '' OR 1=1 --' — returning every user.DefenceParameterised queries / Prepared Statements — the only reliable protection. Data and SQL code are always separate at the database protocol levelORM — most modern ORMs use prepared statements automaticallyWhitelist validation — verify the value is in an allowed list, not just escape itNever concatenate user data directly into an SQL string, even after addslashes()
SQL Window Functions
Window functions compute a value for each row relative to a related set of rows (the "window"), without collapsing them into one. They enable rankings, running totals, and comparisons without subqueries.SyntaxSELECT
name,
salary,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rank,
SUM(salary) OVER (PARTITION BY dept) AS dept_total,
AVG(salary) OVER () AS company_avg
FROM employees;Common functionsROW_NUMBER() — sequential number within the windowRANK() / DENSE_RANK() — rank (with gaps / without gaps)LAG(col, n) / LEAD(col, n) — value from the previous/next rowSUM / AVG / MAX OVER (...) — aggregates over the window without GROUP BYVs GROUP BYGROUP BY collapses rows into one. A window function keeps all rows and adds a computed value to each.
SSH
SSH (Secure Shell) is a protocol for securely connecting to a remote server over a network. It replaced the insecure Telnet, which sent data in plain text. Every developer who deploys to a VPS or uses a Git repository uses SSH daily.AuthenticationPassword-based — convenient but vulnerable to brute force. Better to disable itKey-based — a private/public key pair. The private key stays with you; the public key goes on the server in ~/.ssh/authorized_keys. Secure and convenientCommon commandsssh user@server.com # connect
ssh-keygen -t ed25519 # generate keys
ssh-copy-id user@server.com # copy public keySSH TunnelingSSH lets you forward a local port through an encrypted tunnel — for example, connecting to a production database from your laptop without exposing the DB port to the internet.
SSR (Server-Side Rendering)
SSR (Server-Side Rendering) is the generation of HTML on the server for every request, sending fully rendered markup to the browser. The browser receives complete HTML immediately, without waiting for JavaScript. The opposite is CSR (Client-Side Rendering, i.e. SPA).SSR advantagesSEO — search bots see all content immediatelyFirst paint — content is visible before JavaScript executesLow-end devices — less work for the browserDisadvantagesEvery request is server work, increasing loadSlower navigation (compared to SPA) without streaming or partial renderingApproachesTraditional SSR — PHP, Ruby, Python render HTML templates. Battle-tested for yearsHydration — the server renders HTML; the client "hydrates" it with JS components (Next.js, Nuxt)Static Generation (SSG) — HTML is built at deploy time, not at request time. Fastest possible
SSRF (Server-Side Request Forgery)
SSRF is an attack where an attacker tricks a server into making an HTTP request to an arbitrary address on its behalf. The server "proxies" the request — giving the attacker access to resources unreachable from outside: internal services, cloud metadata endpoints, the local network.
Example
An application loads images from a user-supplied URL: fetch_image?url=http://.... The attacker passes url=http://169.254.169.254/latest/meta-data/ — the AWS metadata endpoint. The server fetches IAM tokens and returns them.
Defence
Whitelist of allowed domains — do not trust arbitrary user-supplied URLs
Block requests to private IPs: 127.0.0.1, 10.x, 172.16-31.x, 192.168.x, 169.254.x
Validate the IP after DNS resolution — DNS rebinding bypasses hostname checks
IMDSv2 on AWS — token-based access to metadata
Stack and Queue (data structures)
Stack and Queue are basic linear data structures with different access patterns. Stack: last in, first out (LIFO). Queue: first in, first out (FIFO).Stack (LIFO)push(A), push(B), push(C)
pop() → C
pop() → BUses: call stack, undo/redo, expression parsing, depth-first tree traversal (DFS).Queue (FIFO)enqueue(A), enqueue(B), enqueue(C)
dequeue() → A
dequeue() → BUses: task queues, breadth-first search (BFS), producer-consumer buffers.DequeDouble-ended queue — add and remove from both ends. Combines capabilities of both stack and queue.
Static Analysis (PHPStan, Psalm)
Static analysis is automatic code checking without executing it. It finds type errors, unreachable code, and incorrect method calls during CI — before a bug reaches production.
PHPStan
The most popular PHP analyser. 10 strictness levels (0–10). Level 0 covers basic errors; level 9 checks every line for type correctness.
vendor/bin/phpstan analyse src --level=6
Psalm
An alternative from Vimeo. Stricter, supports @template generics and taint analysis (detecting SQL injection and XSS through data flow).
What it finds
Calling a method on a null value
Passing the wrong type to a function
Unreachable code after a return
Unused variables and imports
Non-exhaustive match expressions
Stored Procedure
A stored procedure is a subroutine of SQL logic stored directly in the DBMS and called by name. Unlike a regular query — it is compiled once, executes faster, and can have input/output parameters.
Example (MySQL)
DELIMITER $$
CREATE PROCEDURE GetUserOrders(IN userId INT)
BEGIN
SELECT o.id, o.total, o.status
FROM orders o
WHERE o.user_id = userId
ORDER BY o.created_at DESC;
END$$
DELIMITER ;
-- Call
CALL GetUserOrders(42);
Benefits
Logic at the DB level — independent of the application language
Less traffic between application and database
Permissions at the procedure level, not the table level
Drawbacks
Hard to test and version (not in Git)
Business logic scattered between code and database
Tied to a specific DBMS
Strangler Fig Pattern
Strangler Fig is a strategy for gradually migrating a monolithic system to a new architecture. New code "grows around" the old system — like a strangler fig tree around its host — progressively replacing it without stopping the system.
How it works
A proxy (API Gateway or Nginx) is placed in front of the monolith
New features are built in new microservices
Portions of monolith functionality are progressively moved to new services
The proxy switches traffic from the monolithic endpoint to the new one
When all functionality is moved, the monolith is shut down
Benefits
Zero risk: can roll back to the monolithic endpoint at any time
The system stays running throughout the migration
The team gradually builds microservices experience
Alternative
Big Bang rewrite — rewrite everything at once. Statistically the most failure-prone approach for large systems.
Strategy Pattern
Strategy is a pattern that extracts a varying behaviour into a separate class (the strategy) and allows it to be swapped at runtime. The class depends on the strategy interface, not on a concrete implementation.Exampleinterface SortStrategy {
sort(array $data): array;
}
class QuickSort implements SortStrategy { ... }
class MergeSort implements SortStrategy { ... }
class Sorter {
public function __construct(private SortStrategy $strategy) {}
public function sort(array $data): array {
return $this->strategy->sort($data);
}
}When to useThere are multiple variants of an algorithm and you need to switch between themYou want to avoid large if/switch blocks selecting the algorithmThe behaviour should be configurable from outside or changeable at runtime
Strict Types (strict_types)
strict_types is a PHP directive that enables strict type enforcement: if a function expects an int and receives a string, a TypeError is thrown instead of silently coercing the value. Adds safety and explicitness to the code.