The Complete Software Architecture Database
Production implementations for the 10 most popular programming languages.
1. Python: Async Web Scraper
PythonFetching pages in parallel using asyncio, httpx, and BeautifulSoup.
import asyncio
import httpx
from bs4 import BeautifulSoup
class AsyncScraper:
def __init__(self, urls):
self.urls = urls
async def fetch(self, client, url):
try:
r = await client.get(url, timeout=10.0, follow_redirects=True)
if r.status_code == 200:
soup = BeautifulSoup(r.text, 'html.parser')
return {"url": url, "title": soup.title.string.strip() if soup.title else ""}
except Exception as e:
return {"url": url, "error": str(e)}
async def run(self):
async with httpx.AsyncClient() as client:
return await asyncio.gather(*[self.fetch(client, u) for u in self.urls])
Automatic retrying of failed network requests with delay.
import time
from functools import wraps
def retry(retries=3, delay=2):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
attempts = 0
while attempts < retries:
try:
return func(*args, **kwargs)
except Exception as e:
attempts += 1
if attempts == retries: raise e
time.sleep(delay)
return wrapper
return decorator
Secure decoding and validation of authorization headers (PyJWT).
import jwt
import os
# UWAGA: nigdy nie zapisuj sekretu na stałe w kodzie.
# Wczytaj go ze zmiennej środowiskowej.
SECRET_KEY = os.environ["JWT_SECRET_KEY"]
ALGORITHM = "HS256"
def verify_token(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return {"valid": True, "payload": payload}
except jwt.ExpiredSignatureError:
return {"valid": False, "error": "Token wygasł"}
except jwt.InvalidTokenError:
return {"valid": False, "error": "Nieprawidłowy token"}
Protection against XSS and code injection using html.escape.
import html
def sanitize_input(user_input):
if not isinstance(user_input, str):
return ""
return html.escape(user_input.strip())
Sending advanced system status reports via API.
import requests
def send_telegram_message(token, chat_id, message):
url = f"https://api.telegram.org/bot{token}/sendMessage"
payload = {"chat_id": chat_id, "text": message, "parse_mode": "Markdown"}
response = requests.post(url, json=payload)
return response.json()
Middleware that protects endpoints from DDoS and brute-force attacks.
const rateLimit = require('express-rate-limit');
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
message: { status: 429, error: "Zbyt wiele żądań, spróbuj później." }
});
Secure authorization of incoming requests using HMAC SHA256.
const crypto = require('crypto');
function verifyWebhookSignature(req, secretKey) {
const signature = req.headers['x-hub-signature-256'];
if (!signature) return false;
const hmac = crypto.createHmac('sha256', secretKey);
const digest = `sha256=${hmac.update(req.rawBody).digest('hex')}`;
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest));
}
8. JavaScript: Task Queue with Concurrency
JavaScriptControlling the number of concurrently running background operations.
class TaskQueue {
constructor(concurrency = 2) {
this.concurrency = concurrency;
this.running = 0;
this.queue = [];
}
add(task) {
return new Promise((resolve, reject) => {
this.queue.push({ task, resolve, reject });
this.next();
});
}
next() {
if (this.running >= this.concurrency || this.queue.length === 0) return;
this.running++;
const { task, resolve, reject } = this.queue.shift();
task().then(resolve).catch(reject).finally(() => { this.running--; this.next(); });
}
}
Generating salted hashes and verifying them with bcrypt.
const bcrypt = require('bcrypt');
async function hashPassword(plainPassword) {
return await bcrypt.hash(plainPassword, 10);
}
async function verifyPassword(plainPassword, hashed) {
return await bcrypt.compare(plainPassword, hashed);
}
10. JavaScript: Robust Fetch with Timeout
JavaScriptAn HTTP client resilient to hanging microservices (AbortController).
async function robustFetch(url, options = {}, timeoutMs = 5000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, { ...options, signal: controller.signal });
clearTimeout(timer);
if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
return await res.json();
} catch (err) {
clearTimeout(timer);
throw err;
}
}
11. TypeScript: DI Container (Generics)
TypeScriptA manual implementation of the inversion-of-control pattern using generics.
class Container {
private services = new Map();
register(name: string, instance: T): void {
this.services.set(name, instance);
}
resolve(name: string): T {
const service = this.services.get(name);
if (!service) throw new Error(`Service not found: ${name}`);
return service as T;
}
}
12. TypeScript: Environment Variable Parser
TypeScriptValidating environment configuration using the Zod library.
import { z } from 'zod';
const envSchema = z.object({
PORT: z.string().transform(Number),
DATABASE_URL: z.string().url(),
NODE_ENV: z.enum(['development', 'production'])
});
export const env = envSchema.parse(process.env);
13. TypeScript: Generic Repository Pattern
TypeScriptDatabase operation abstraction for arbitrary TypeScript models.
interface IRepository {
findById(id: string): Promise;
save(entity: T): Promise;
}
class InMemoryRepository implements IRepository {
private items = new Map();
async findById(id: string): Promise { return this.items.get(id) || null; }
async save(entity: T): Promise { this.items.set(entity.id, entity); }
}
14. TypeScript: Runtime Struct Validator
TypeScriptDeep type checking of nested objects via Type Guards.
interface User { id: string; name: string; }
function isUser(obj: any): obj is User {
return obj
&& typeof obj === 'object'
&& typeof obj.id === 'string'
&& typeof obj.name === 'string';
}
15. TypeScript: Strongly Typed Logger
TypeScriptA production event logging system with log-level interfaces.
type LogLevel = 'INFO' | 'WARN' | 'ERROR';
class TypedLogger {
private log(level: LogLevel, message: string, meta?: Record) {
console.log(JSON.stringify({ timestamp: new Date().toISOString(), level, message, ...meta }));
}
info(msg: string, meta?: Record) { this.log('INFO', msg, meta); }
error(msg: string, meta?: Record) { this.log('ERROR', msg, meta); }
}
Lazy initialization with double-checked locking in a multithreaded environment.
public class SecureSingleton {
private static volatile SecureSingleton instance;
private SecureSingleton() {}
public static SecureSingleton getInstance() {
if (instance == null) {
synchronized (SecureSingleton.class) {
if (instance == null) {
instance = new SecureSingleton();
}
}
}
return instance;
}
}
Async processing of task batches using Future objects.
import java.util.concurrent.*;
public class TaskProcessor {
public static void run() {
ExecutorService executor = Executors.newFixedThreadPool(4);
Future future = executor.submit(() -> {
Thread.sleep(1000);
return "Wynik zadania w tle";
});
executor.shutdown();
}
}
An advanced network request using Java's native API.
import java.net.URI;
import java.net.http.*;
public class ApiClient {
public static String get(String url) throws Exception {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
}
}
Intercepting HTTP traffic, logging execution time, and validation.
import jakarta.servlet.*;
import java.io.IOException;
public class LoggingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
long start = System.currentTimeMillis();
chain.doFilter(req, res);
long duration = System.currentTimeMillis() - start;
System.out.println("Czas zapytania: " + duration + "ms");
}
}
Efficient copying and buffering of large files via streaming.
import java.nio.file.*;
public class FileManager {
public static void copy(String source, String target) throws Exception {
Path srcPath = Paths.get(source);
Path destPath = Paths.get(target);
Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING);
}
}
A universal data-access layer with async support.
public class Repository where T : class {
private readonly DbContext _context;
private readonly DbSet _dbSet;
public Repository(DbContext context) {
_context = context;
_dbSet = context.Set();
}
public async Task GetByIdAsync(int id) => await _dbSet.FindAsync(id);
}
Catching errors in ASP.NET Core and returning JSON.
public class ExceptionMiddleware {
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context) {
try { await _next(context); }
catch (Exception ex) {
context.Response.StatusCode = 500;
await context.Response.WriteAsJsonAsync(new { error = ex.Message });
}
}
}
A long-running background process that performs recurring system tasks.
public class TimedWorker : BackgroundService {
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
}
}
}
Configuring strongly typed application settings in .NET.
public class SmtpSettings {
public string Host { get; set; } = string.Empty;
public int Port { get; set; }
}
// Rejestracja: builder.Services.Configure(builder.Configuration.GetSection("Smtp"));
Fetching data with a locking mechanism that prevents overload.
using Microsoft.Extensions.Caching.Memory;
public class CachedService {
private readonly IMemoryCache _cache;
public async Task GetDataAsync(string key) {
return await _cache.GetOrCreateAsync(key, async entry => {
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return await FetchFromDatabaseAsync();
});
}
private Task FetchFromDatabaseAsync() => Task.FromResult("Dane");
}
Safe use of std::unique_ptr and std::shared_ptr.
#include <memory>
class Node {
public:
int value;
std::shared_ptr<Node> next;
Node(int val) : value(val) {}
};
void createList() {
auto head = std::make_shared<Node>(10);
head->next = std::make_shared<Node>(20);
}
A task queue based on std::mutex and condition_variable.
#include <vector>
#include <thread>
#include <queue>
#include <mutex>
class SimplePool {
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_lock;
};
Fast processing of large text files without allocation.
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string&s, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::stringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
A circular buffer for low-overhead inter-thread communication.
#include <atomic>
#include <vector>
template<typename T, size_t Size>
class RingBuffer {
T data[Size];
std::atomic<size_t> head{0};
std::atomic<size_t> tail{0};
};
Conditional log compilation depending on debug flags.
#include <iostream>
#ifdef DEBUG_MODE
#define LOG(msg) std::cout << "[DEBUG] " << msg << std::endl;
#else
#define LOG(msg)
#endif
Handling requests with context.Context propagation and safe shutdown.
package main
import (
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
http.ListenAndServe(":8080", mux)
}
Distributing tasks across a fixed number of concurrent workers.
package main
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
results <- j * 2
}
}
func startPool() {
jobs := make(chan int, 100)
results := make(chan int, 100)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
}
Implementation of a network traffic throughput algorithm.
package main
import "golang.org/x/time/rate"
var limiter = rate.NewLimiter(1, 5)
func checkLimit() bool {
return limiter.Allow()
}
Checking tokens and injecting session data into the context.
package main
import "net/http"
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token != "Bearer secret" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
Configuring optimal database connection limits.
package main
import (
"database/sql"
"time"
)
func configurePool(db *sql.DB) {
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
}
Matching URLs to controllers with parameters.
class Router {
private array $routes = [];
public function add(string $method, string $path, callable $handler): void {
$this->routes[$method][$path] = $handler;
}
public function dispatch(string $method, string $uri): mixed {
return $this->routes[$method][$uri]() ?? http_response_code(404);
}
}
Prepared statements resistant to SQL Injection.
function transferFunds(PDO $pdo, int $from, int $to, float $amount): void {
try {
$pdo->beginTransaction();
// Operacje SQL...
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
throw $e;
}
}
Checking user permissions against resources.
class RBAC {
private array $roles = ['admin' => ['delete', 'write', 'read'], 'user' => ['read']];
public function hasPermission(string $role, string $permission): bool {
return in_array($permission, $this->roles[$role] ?? []);
}
}
A parser and dispatcher for async tasks, driven from the console.
class TaskDispatcher {
public function dispatch(string $jobClass, array $data): void {
$payload = json_encode(['job' => $jobClass, 'data' => $data]);
file_put_contents(__DIR__ . '/queue.log', $payload . PHP_EOL, FILE_APPEND);
}
}
Cryptographically securing data sent between systems.
function signData(string $data, string $privateKey): string {
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256);
return base64_encode($signature);
}
Sharing state across multiple threads without data races.
use std::sync::{Arc, Mutex};
use std::thread;
fn create_counter() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
}));
}
}
Idiomatic handling of missing data and parsing errors.
fn parse_port(s: &str) -> Result {
s.trim().parse::()
}
Handling incoming connections using multithreading.
use std::net::TcpListener;
fn run_server() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080")?;
for stream in listener.incoming() {
let _stream = stream?;
// Obsługa połączenia...
}
Ok(())
}
Processing collections with compiler optimizations.
fn sum_evens(numbers: &[i32]) -> i32 {
numbers.iter()
.filter(|&&x| x % 2 == 0)
.sum()
}
Measuring the performance of code fragments in a transparent way.
macro_rules! time_it {
($body:expr) => {
let start = std::time::Instant::now();
let _res = $body;
println!("Czas wykonania: {:?}", start.elapsed());
};
}
Trend analysis and rankings (ROW_NUMBER) over time.
SELECT
department_id,
employee_name,
salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) as rank_in_dep
FROM employees;
Safe modification of inventory states or financial balances.
BEGIN TRANSACTION;
SELECT stock_quantity
FROM inventory
WHERE product_id = 142
FOR UPDATE;
UPDATE inventory
SET stock_quantity = stock_quantity - 1
WHERE product_id = 142;
COMMIT;
A function that refreshes the modification field on every UPDATE.
CREATE TRIGGER update_timestamp
BEFORE UPDATE ON users
FOR EACH ROW
SET NEW.updated_at = CURRENT_TIMESTAMP;
Indexing only active records to save memory.
CREATE INDEX idx_active_users_email
ON users(email)
WHERE status = 'active';
Traversing hierarchical relationships (e.g. an organization chart).
WITH RECURSIVE org_chart AS (
SELECT id, name, manager_id, 1 as level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.level + 1
FROM employees e
JOIN org_chart o ON e.manager_id = o.id
)
SELECT * FROM org_chart;