今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

标签:#backend

找到 94 篇相关文章

AI 资讯

Why Retries Are More Dangerous Than Failures in Production Systems

Failures are obvious. Retries are sneaky. When something fails, everyone notices. An alert goes off. A request errors out. Someone starts investigating. Retries are different. They look harmless. Most of the time, they save the system. But sometimes, retries create bigger problems than the original failure. Imagine an API call times out. No problem. The system retries. But what if the first request actually succeeded and only the response was lost? Now the retry creates: duplicate orders repeated emails inconsistent records workflows running twice The failure happened once. The retry multiplied it. Another thing I've seen: One slow dependency causes requests to pile up. Retries start firing. Those retries create even more traffic. Which slows things down further. Which triggers even more retries. Suddenly, the system is spending more effort retrying than doing useful work. Retries also hide problems. A temporary issue gets retried five times and eventually succeeds. Everything looks normal. Meanwhile: latency increases queues grow users experience delays Nothing technically failed. But the system is getting less healthy. What changed for me is that I stopped treating retries as free. Every retry has a cost. It consumes resources. It increases load. And if actions aren't designed carefully, retries can repeat side effects that should only happen once. Now when I build something, I don't ask: "What happens if this fails?" I ask: "What happens if this runs again?" Because in production, things almost always run again. And if the answer is "bad things happen," the retry mechanism isn't helping. It's making things worse. Failures are part of every system. Retries are too. The difference is that failures usually happen once. Retries can turn one problem into hundreds if you don't design for them. This is something we think about constantly at BrainPack when operating long-running workflows across multiple systems. AI and automation layers make retries even more common, wh

2026-06-19 原文 →
AI 资讯

Go's Type System — Structs, Interfaces, and Life Without Inheritance

Go's Type System — Structs, Interfaces, and Life Without Inheritance In part 1 of this series I talked about why I'm picking up Go after six years of Java and Kotlin, plus a recent deep dive into Rust. This time I want to get into the part that actually changed how I think about designing code: Go has no class inheritance at all. Coming from the JVM world, that sentence sounded alarming the first time I read it. No extends . No abstract classes. No polymorphism through a class hierarchy. And yet Go backends at companies running serious scale seem to do just fine without it. After a few weeks living inside Go's type system, I get why. Structs: Data, Nothing More A Go struct is just a typed bag of fields. No constructors, no access modifiers in the Java sense, no inheritance: type Order struct { ID string Customer string Amount float64 Status string } func NewOrder ( id , customer string , amount float64 ) Order { return Order { ID : id , Customer : customer , Amount : amount , Status : "pending" , } } That NewOrder function is doing the job a constructor would do in Java — it's just a plain function by convention, not a language feature. Nothing stops you from building an Order{} directly with zero values either, which takes some adjusting to if you're used to constructors enforcing invariants. Methods attach to structs separately, outside the type definition: func ( o Order ) Total () float64 { return o . Amount } func ( o * Order ) MarkPaid () { o . Status = "paid" } That (o Order) vs (o *Order) distinction is the receiver type, and it trips up a lot of newcomers. A value receiver gets a copy of the struct; a pointer receiver can mutate the original. MarkPaid has to use a pointer receiver, or the status change would vanish the moment the method returns. No Inheritance, So What Replaces It? This is the part that took the most rewiring. In Java, if PremiumOrder needed everything Order had plus more, you'd write class PremiumOrder extends Order . Go simply doesn't hav

2026-06-19 原文 →
AI 资讯

Exploring Lore: A Scalable Open Source Version Control System

What was released / announced Lore is an open source version control system designed with scalability in mind, allowing developers to efficiently manage large-scale projects. According to the official website, Lore aims to provide a more efficient and scalable alternative to traditional version control systems. This release is particularly exciting for developers and engineers working on complex projects that require robust version control. Why it matters As someone who works with large-scale AI infrastructure and cloud systems, I can attest to the importance of reliable version control. With Lore, developers can expect improved performance and reduced latency when managing massive codebases. This is especially crucial in environments where multiple teams collaborate on the same project, and version control becomes a bottleneck. I believe Lore has the potential to streamline development workflows and enhance overall productivity. How to use it To get started with Lore, you can begin by installing the command-line tool using the following command: pip install lore Once installed, you can initialize a new Lore repository using: lore init Lore also provides a REST API for integrating with other tools and services. For example, you can use the following Python code snippet to interact with the Lore API: import requests response = requests . get ( ' https://your-lore-instance.com/api/repo ' ) print ( response . json ()) You can explore more API endpoints and usage examples in the official Lore documentation. My take As an AI infrastructure engineer and DevOps architect, I'm excited about the potential of Lore to improve our development workflows. In my experience, traditional version control systems often struggle with large-scale projects, leading to performance issues and frustration. Lore's focus on scalability and performance could be a game-changer for teams working on complex AI and machine learning projects. I'm looking forward to exploring Lore further and integr

2026-06-19 原文 →
AI 资讯

Day 41 of Learning MERN stack

Hello Dev Community! 👋 It is officially Day 41 of my continuous streak toward full-stack MERN engineering! Yesterday, I migrated my codebase from native Node boilerplate to Express.js. Today, I dived straight into the absolute core mechanism that makes Express so incredibly powerful in Prashant Sir's (Complete Coding) masterclass : Middlewares . Before today, I thought requests hit an endpoint and immediately returned a response. Today, I learned how to intercept, inspect, and modify that request before it ever reaches the final route handler! 🧠 Key Learnings From Node.js Lecture 9 (Middlewares) A middleware is essentially a function that executes during the Request-Response cycle, having full access to the req , res , and the next middleware function in line. Here is the technical breakdown: 1. The Anatomy of Middleware Unlike a standard route handler that takes (req, res) , a middleware takes a third powerful argument: next . If you don't invoke next() , your request will hang forever and the browser will eventually timeout! 2. Built-in vs. Custom Middleware Custom Middleware: Wrote my own custom functions using app.use((req, res, next) => { ... }) to act as a security guard or global logger. Built-in Middleware: Explored how Express natively handles data types using structures like express.json() and express.urlencoded() , which automatically parse inbound request bodies so we don't have to manually handle streams anymore! javascript const express = require("express"); const app = express(); // Custom Global Logging Middleware app.use((req, res, next) => { console.log(`[${new Date().toISOString()}] ${req.method} request to ${req.url}`); next(); // Pass control to the next handler in line! }); app.get("/dashboard", (req, res) => { res.send("Welcome to the secure dashboard layer!"); }); app.listen(8000);

2026-06-18 原文 →
AI 资讯

Day 39 of Learning MERN Stack

Hello Dev Community! 👋 It is officially Day 39 of my non-stop run toward full-stack MERN engineering! Yesterday, I mapped out basic HTTP verbs like GET and POST. Today, I advanced into Prashant Sir's (Complete Coding) backend masterclass to tackle one of the most critical core operations: Handling Data Streams and Body Parsing . When a user submits a form or uploads data, the server doesn't receive the file all at once. It arrives as an asynchronous stream of network data chunks. Today, I learned how to collect and decode those packets natively! 🧠 Key Learnings From Node.js Lecture 7 (Streams & Buffers) Node.js is designed to be non-blocking and memory-efficient. Here is the technical breakdown of how it intercepts client payloads: 1. Inbound Streams & Data Chunks I learned that incoming POST data is treated as a Readable Stream . Instead of loading a massive data file into the server memory instantly, Node transmits the payload in tiny pieces called Chunks (hexadecimal binary data). 2. Event Listeners for Requests ( req.on ) Natively, we don't have an instant req.body object. We have to listen to the network events on the incoming request stream: req.on("data", (chunk) => { ... }) : Fires every single time a fresh chunk of binary data arrives at the network interface. We push these raw chunks into a temporary array. req.on("end", () => { ... }) : Fires automatically once the stream concludes and all chunks have arrived safely. javascript if (req.url === "/submit" && req.method === "POST") { let body = []; req.on("data", (chunk) => { body.push(chunk); // Collecting raw binary chunks }); req.on("end", () => { // Concatenating and converting hexadecimal binary buffers into a readable string layout let parsedBody = Buffer.concat(body).toString(); console.log("Received Form Payload:", parsedBody); res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Data received and parsed successfully!"); }); }

2026-06-17 原文 →
AI 资讯

Day 38 of Learning MERN Stack

Hello Dev Community! 👋 It is officially Day 38 of my unbroken streak toward mastering the MERN stack! Yesterday, I learned how to extract query strings from the URL bar. Today, I took a massive step forward into full-stack backend architecture by diving into Prashant Sir's (Complete Coding) roadmap to master HTTP Request Methods . Up until now, our server treated every incoming request the same way. Today, I learned how to make the backend execute completely different actions based on the "intent" (HTTP Verb) of the user! 🧠 Key Learnings From Node.js Lecture 6 (HTTP Verbs) An endpoint is no longer static when you map request methods against it. Here is the technical breakdown of what I locked down today: 1. Cracking req.method I discovered that the incoming Request object holds a crucial property called req.method . This tells the server exactly what action the client wants to perform. 2. The Big Four Core Methods GET: Used when the user simply wants to read or fetch data from the server (e.g., viewing a product page). POST: Used when the user wants to securely send or create new data on the server (e.g., submitting a signup form). PUT/PATCH: Used to update existing data records. DELETE: Used to wipe a specific data entry from the server storage. javascript const http = require("http"); const server = http.createServer((req, res) => { if (req.url === "/api/data") { if (req.method === "GET") { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Fetching and reading secure database records..."); } else if (req.method === "POST") { res.writeHead(201, { "Content-Type": "text/plain" }); res.end("Securely creating and injecting new data into the server!"); } } else { res.end("Standard Route"); } }); server.listen(8000);

2026-06-17 原文 →
AI 资讯

Day 37 of Learning MERN Stack

Hello Dev Community! 👋 It is officially Day 37 of my continuous streak toward mastering the MERN stack! Yesterday, I configured clean structural routing to map pages like /about or /contact . Today, I advanced further into Prashant Sir's (Complete Coding) backend roadmap to tackle an essential data communication concept: URL Parsing and Query Parameters . When a user searches for something or filters products on an e-commerce platform, that data is passed directly inside the URL string. Today, I learned how to intercept and decode that data natively! 🧠 Key Learnings From Node.js Lecture 5 (The URL Module) An incoming URL is much more than just a text path; it is a complex structured object. Here is the technical breakdown of how I dissected it today: 1. Ingesting the Native url Module I explored Node's legacy and modern URL parsing engines. By passing the raw req.url string into the parser, Node breaks down the web address into a fully accessible metadata object. 2. Dissecting Pathname vs Query String I learned the difference between the structural endpoint location and the dynamic data payload: Pathname: The core location path (e.g., /search or /api/products ). Query: The actual data key-value strings attached after the question mark ? (e.g., ?name=ali&id=7 ). javascript const http = require("http"); const url = require("url"); const server = http.createServer((req, res) => { // Parsing the URL path and query parameters together cleanly let parsedUrl = url.parse(req.url, true); let pathname = parsedUrl.pathname; let queryData = parsedUrl.query; // Converts query text into a clean JS Object! if (pathname === "/search") { res.writeHead(200, { "Content-Type": "text/plain" }); res.end(`Searching logs for user: ${queryData.name} with ID: ${queryData.id}`); } else { res.end("Standard Endpoint View"); } }); server.listen(8000);

2026-06-17 原文 →
AI 资讯

AI for API Design & Testing in 2026: Speakeasy vs Swagger AI vs Postman AI — I Built 3 APIs with Each

AI for API Design & Testing in 2026: Speakeasy vs Swagger AI vs Postman AI — I Built 3 APIs with Each API design is one of the most tedious parts of backend development. Writing OpenAPI specs, generating SDKs, testing endpoints, maintaining documentation — it's all hours of work that could be automated. In 2026, three tools are fighting for your API workflow: Speakeasy , Swagger AI , and Postman AI . I spent 4 weeks building the same REST API with each one, tracking time savings, code quality, and actual developer experience. Here's what actually happened. The Test Setup: Building a Real API I built a simple but realistic ecommerce API (GET/POST products, orders, user management) three separate times, measuring: Time to spec — writing the OpenAPI definition Time to SDK generation — generating client libraries Time to testing — setting up test cases and running them Documentation quality — readability, examples, completeness Iteration speed — how fast you can modify the API and regenerate everything All three tools were given the same requirements. Same laptop, same environment, same skill level (senior backend engineer). Speakeasy: The SDK Generation King Setup time: 8 minutes (CLI install, auth, first config) Learning curve: Low — clear docs, straightforward CLI Speakeasy is laser-focused on one problem: turning your API spec into production-ready SDKs. It generates TypeScript, Python, Go, Java, and more from a single OpenAPI definition. The Good SDK quality is exceptional. The generated TypeScript SDK was production-grade immediately — proper error handling, retry logic, request/response typing, retries built in. No cleanup work needed. Multi-language generation is instant. After writing the OpenAPI spec once, I had Python, Go, and TypeScript SDKs in < 2 minutes total. Each one was framework-idiomatic (using popular libraries in each language). Versioning is smart. Speakeasy automatically versioned SDKs and generated changelogs. When I modified the spec, it detect

2026-06-17 原文 →
AI 资讯

Comparable vs Comparator in Java

In Java, sorting is an important operation when working with collections such as ArrayList, LinkedList, and other data structures. For primitive data types, Java already knows how to sort values. However, for custom objects like Student, Employee, or Product, Java needs instructions on how objects should be compared. To achieve this, Java provides two interfaces: Comparable – Used for natural sorting. Comparator – Used for custom sorting. Comparable Interface Comparable is an interface available in the java.lang package. It is used to define the natural ordering of objects. The sorting logic is written inside the class itself using the compareTo() method. Method int compareTo(T obj) Return Values Negative - Current object comes before the given object Zero - Both objects are equal Positive - Current object comes after the given object When to Use Comparable? Use Comparable when: A class has one default sorting order. The sorting logic is a natural property of the object. The sorting criteria rarely change. Comparator Interface Comparator is an interface available in the java.util package. It is used to define custom sorting logic outside the class. Multiple comparators can be created for the same class. Method int compare(T o1, T o2) Return Values Negative - First object comes before second object Zero - Both objects are equal Positive - First object comes after second object When to Use Comparator? Use Comparator when: Multiple sorting criteria are required. You don't want to modify the original class. Different sorting orders are needed at different times.

2026-06-16 原文 →
AI 资讯

Recap — M0 Foundations

This module built one thing, from many angles: the container — the part of Spring that creates your objects, wires them together, and hands them out. Eight articles each zoomed in on a different corner of it. This recap zooms back out. The goal here is not to re-explain each topic, but to show how they are all the same idea seen from different sides, so the whole module collapses into a picture you can hold in your head at once. So before the details, here is the single sentence the entire module hangs on: the container is a factory that runs at startup, and almost every feature you met is just that factory doing a little extra work while it builds a bean. Keep that sentence close. Everything below is a way of filling it in. The factory, in one picture Picture an assembly line that runs exactly once, when your application boots. You hand it a list of what to build and how the pieces fit. It builds every object your app is made of, connects them, sets them on a shelf, and hands them out on request for the rest of the program's life. That assembly line is the container. The objects it builds and manages are beans . An object you create yourself with new is not a bean — Spring never touched it — and that distinction is the thread running through every trap in this module. The factory does four things at startup, and the order matters: it reads recipes, works out who needs whom, builds from the bottom up, and caches each result. ApplicationContext ctx = SpringApplication . run ( App . class , args ); OrderService svc = ctx . getBean ( OrderService . class ); // already built and wired By the time run returns, the work is done. Asking for a bean is instant because the building already happened. Every other topic in the module is a detail about how that one startup pass works. Why we hand the work over at all The module opened with a question of control. Left alone, a class builds its own collaborators with new — and in doing so it welds together two unrelated decisions:

2026-06-16 原文 →
AI 资讯

REST vs GraphQL vs gRPC — Which One Should You Actually Use?

Every engineering team hits this conversation at some point. Someone proposes GraphQL. Someone else says REST is fine. A third person mentions gRPC and half the room goes quiet. The debate usually ends with the most senior person in the room picking what they're most familiar with. That's not a strategy — that's habit. Here's an objective breakdown of all three, when each one wins, and how to actually make the decision for your specific use case. The Core Mental Model Before comparing them, understand what each one is optimizing for: REST optimizes for simplicity and broad compatibility GraphQL optimizes for flexibility and precise data fetching gRPC optimizes for performance and strongly-typed contracts None of them is universally better. Each one is a tradeoff. The right answer depends entirely on who is consuming your API and what they need from it. REST — The Default That Still Wins Most of the Time REST (Representational State Transfer) is not a protocol. It's an architectural style built on HTTP — verbs, URLs, and status codes most developers already understand. Where REST genuinely wins: Public APIs. If external developers are consuming your API, REST is the only reasonable default. The tooling, documentation patterns, and developer familiarity are unmatched. Stripe, Twilio, GitHub — all REST. Simple CRUD services. If your resource model is straightforward, REST maps cleanly to it. No overhead, no learning curve, no ceremony. Browser-native requests. REST over HTTP works directly in the browser without any special client. Fetch it, done. Where REST struggles: Over-fetching and under-fetching. A single REST endpoint returns a fixed shape. Mobile clients that need 3 fields get 40. Separate data needs often require multiple round trips. Versioning overhead. As covered in our previous post — every breaking change forces a versioning decision. This compounds quickly on complex APIs. GraphQL — Powerful, But You Need to Earn It GraphQL is a query language for your A

2026-06-16 原文 →
开发者

Challenges I Faced and How GoFr Helped

Why I Chose GoFr for My Backend Project When starting a new backend project, one of the first decisions I need to make is choosing the right framework. Over the years, I’ve experimented with different backend technologies, each offering its own strengths and trade-offs. For my latest project, however, I decided to try something different: GoFr. At first, I was simply exploring the Go ecosystem and looking for tools that could help me build production-ready services faster. What caught my attention wasn’t just that GoFr was built in Go—it was the philosophy behind it. Instead of forcing developers to spend days configuring infrastructure, wiring dependencies, and setting up observability, GoFr focuses on helping developers get from idea to deployment quickly. In this article, I’ll share the reasons why I chose GoFr for my backend project and what stood out during my experience. The Problem with Starting Backend Projects Every backend project begins with excitement. You have an idea, a feature roadmap, and a vision of what you’re trying to build. Yet before writing meaningful business logic, developers often spend hours or even days configuring: Logging Database connections Metrics Tracing Health checks API routing Environment management Deployment configurations While these tasks are necessary, they rarely contribute directly to solving the actual problem your application is meant to address. As a developer who frequently builds side projects and prototypes, I wanted a framework that reduced this setup overhead while still following good engineering practices. That’s where GoFr entered the picture. What Initially Attracted Me to GoFr The first thing I noticed was how quickly I could get a service running. Instead of navigating through multiple configuration files and third-party packages, GoFr provides many essential backend capabilities out of the box. This means less time deciding which libraries to install and more time focusing on application logic. The framework

2026-06-15 原文 →
AI 资讯

Your Hand-Rolled Two-Phase Commit Between Two Databases Isn't Atomic

I had a write that spanned two physically separate databases. A rename that had to propagate across several tables in one database and a couple of tables in another, and the two had to stay consistent. No distributed transaction coordinator was available to me. So I did the obvious thing: opened a transaction on each, did the work, and committed them one after the other inside a try/catch with rollbacks on both sides. It felt safe. It compiled. It passed tests. Then I drew the failure on a whiteboard, and the safety evaporated. The window that ruins everything Here's the structure, simplified: await using var txA = await dbA . Database . BeginTransactionAsync (); await using var txB = await dbB . Database . BeginTransactionAsync (); await DoWorkOnA ( dbA ); await DoWorkOnB ( dbB ); await txA . CommitAsync (); // <-- succeeds await txB . CommitAsync (); // <-- what if this throws? Two transactions do not make one atomic operation. CommitAsync is a point of no return, and there are two of them. Between the first commit returning and the second one starting, there is a window. If txB fails in that window — the connection drops, the process is killed, the database hiccups — then A is permanently committed and B never happens. Your rollback in the catch block is useless: you can't roll back txA , it's already durable. The two databases now disagree, and nothing in your code will heal that on its own. This is the dual-write problem , and it's not a bug you can fix by being more careful with try/catch. The atomicity you want simply isn't available from two independent commits. Ordering them, nesting them, wrapping them — none of it closes the window, because the window is inherent to having two commit points. Why "it's never failed" isn't reassurance The seductive thing about this pattern is that the window is small, so in practice it almost never triggers. You can run it for a year and never see an inconsistency. That's exactly what makes it dangerous: it trains you to tr

2026-06-15 原文 →
开发者

Building Lightweight PHP Microservices with webrium/core — No Framework Bloat Required

Do you really need a full framework to handle a few API endpoints or webhooks? Laravel and Symfony are excellent tools — for large applications. But when you're building a focused microservice, a webhook receiver, or a lightweight REST API, bootstrapping a full-stack framework means carrying hundreds of files, a massive autoloader, and a dependency tree you'll never fully use. That's the problem webrium/core was built to solve: a minimalist, zero-dependency PHP micro-framework written entirely from scratch, designed to stay out of your way. Installation composer require webrium/core That's it. No configuration files to publish, no service providers to register. The Entry Point Every webrium application starts with the same three lines: <?php require_once __DIR__ . '/vendor/autoload.php' ; use Webrium\App ; use Webrium\Route ; App :: initialize ( __DIR__ ); // ... your routes here App :: run (); App::initialize() sets the root path and loads the global helper functions. App::run() initializes error handling and dispatches the current request through the router. Routing The router supports all standard HTTP methods. Route handlers can be closures, a Controller@method string, or an [Controller::class, 'method'] array. Basic routes: Route :: get ( '/status' , fn () => [ 'status' => 'alive' ]); Route :: post ( '/items' , fn () => [ 'created' => true ]); Route :: put ( '/items/{id}' , fn ( $id ) => [ 'updated' => $id ]); Route :: patch ( '/items/{id}' , fn ( $id ) => [ 'patched' => $id ]); Route :: delete ( '/items/{id}' , fn ( $id ) => [ 'deleted' => $id ]); Route handlers return an array — the framework automatically encodes it as JSON and sends the correct Content-Type header. Dynamic parameters: Route :: get ( '/users/{id}/posts/{postId}' , function ( $id , $postId ) { return [ 'user_id' => $id , 'post_id' => $postId , ]; }); Named routes: Route :: get ( '/users/{id}' , fn ( $id ) => [ 'id' => $id ]) -> name ( 'users.show' ); // Generate the URL elsewhere: $url = rout

2026-06-15 原文 →
AI 资讯

Stop Writing Boilerplate API Responses: Meet BaR-js

We've all been there: you’re building an endpoint, and for the hundredth time, you’re typing out res.status(200).json({ success: true, data: ... }) . It feels repetitive, and honestly, it’s a recipe for inconsistency across your API. I wanted to fix that, so I built BaR-js . What is it? BaR (Builder a Response) is a lightweight, framework-agnostic TypeScript library designed to help you serve API responses like a pro—almost like a bartender mixing a drink. It strips away the JSON clutter and ensures every response you send follows a consistent, production-ready schema. Why use it? Consistency: Every endpoint speaks the same language. Fluent API: You can use a chainable syntax like res.builder.as.ok(data) instead of manually crafting objects every time. Traceability: It automatically handles request_id and timestamps, making debugging so much easier. Type Safety: Built with strict TypeScript, so you get great IntelliSense support. It’s this simple: import express from ' express ' ; import { BarExpressAdapter } from " @vorlaxen-labs/bar-js " ; const app = express (); // 1. Configure the adapter const bar = new BarExpressAdapter ({ environment : ' production ' , logger : console , }); // 2. Register it as middleware // This injects `res.builder` and `req.bar` into every route! app . use ( bar . handler ()); // Now you can use it in any route app . get ( ' /user ' , ( req , res ) => { return res . builder . as . ok ({ name : ' John ' }). build (); }); Why "BaR"? I like the idea that "your code is a work of art, and your responses are its signature." The clearer your response schema, the more professional and valuable your API feels to whoever is consuming it. The project is still fresh, and I’d love to hear what you think. If you’re looking to clean up your API layer, give it a spin! Feedback, issues, or PRs are more than welcome. Check it out on GitHub: https://github.com/vorlaxen-labs/bar-js Grab it from NPM: https://www.npmjs.com/package/@vorlaxen-labs/bar-js Cheers!

2026-06-15 原文 →
AI 资讯

Event-Driven Architecture: Uncle Explains Like You're Five 👦👨‍🦳

A conversation between Uncle (a backend architect) and Nephew (a curious developer) about events, publishers, subscribers, Redis Pub/Sub, RabbitMQ, and Kafka The Beginning: What is an Event? 👦 Nephew: Uncle, I see words like "Redis Pub/Sub", "RabbitMQ", "Kafka" everywhere in job descriptions. What do they all do? Are they the same thing? 👨‍🦳 Uncle: (smiles) No, they're different. But before I confuse you with names, let me ask you something. Have you ever watched the news on TV? 👦 Nephew: Yes uncle, every morning! 👨‍🦳 Uncle: Perfect! So when the news channel says "Breaking News: India won the cricket match" - what happened? 👦 Nephew: Something important occurred... and they announced it! 👨‍🦳 Uncle: Exactly! That "something important occurred" is called an Event . In software, when something happens - like a user placing an order, a payment succeeding, or a file uploading - that's an event. 👦 Nephew: So event = something that happened? 👨‍🦳 Uncle: Yes! Think of it as news. When you place an order at Zomato, that's an event. When you get a payment notification from Google Pay, that's an event. When someone follows you on Instagram, that's an event. 👦 Nephew: Okay, I get it. But uncle, why is this "event" concept important? I can just write code directly, right? 👨‍🦳 Uncle: Ah! That's where the real story begins... The Problem: Spaghetti Code 👨‍🦳 Uncle: Imagine you own a food delivery company. A customer places an order. Now, what all needs to happen? 👦 Nephew: Umm... save the order, send email confirmation, alert the restaurant? 👨‍🦳 Uncle: Good! Let me write the code without events: function placeOrder ( orderId ) { saveOrder ( orderId ); sendEmailConfirmation ( orderId ); sendSMSNotification ( orderId ); notifyRestaurant ( orderId ); updateAnalyticsDashboard ( orderId ); addLoyaltyPoints ( orderId ); updateInventory ( orderId ); } Now, one day your boss says "Also send WhatsApp notification". What do you do? 👦 Nephew: Add another function call in the same code? 👨‍🦳 Unc

2026-06-14 原文 →
AI 资讯

I Built a Consistent Hashing Ring in Pure Python and Finally Understood How Cassandra Distributes Data

I Built a Consistent Hashing Ring in Pure Python and Finally Understood How Cassandra Distributes Data I've been using Cassandra and Redis Cluster for years. I knew consistent hashing was "how they work." But I never truly got it until I built one myself from scratch, in pure Python, with zero dependencies. This post is about what I learned doing that. The Problem Consistent Hashing Solves Imagine you have 3 servers and 1 million keys. The naive approach: server = hash(key) % 3 . It works great until you add or remove a server. Change 3 to 4, and almost every key remaps to a different server. In a caching layer, that means near 100% cache miss. In a database, it means massive data movement. That's the problem consistent hashing solves. When you add or remove a node, only a fraction of keys move. Specifically, 1/n of the keys, where n is the number of nodes. Building the Ring The core idea: place both nodes and keys on a circular number line from 0 to 2^32 (or any large integer). To find which node owns a key, walk clockwise until you hit a node. Here's the minimal version: import hashlib import bisect class ConsistentHashRing : def __init__ ( self , replicas = 150 ): self . replicas = replicas self . ring = {} # hash -> node name self . sorted_keys = [] # sorted hash positions def _hash ( self , key : str ) -> int : return int ( hashlib . md5 ( key . encode ()). hexdigest (), 16 ) def add_node ( self , node : str ): for i in range ( self . replicas ): virtual_key = f " { node } :vnode: { i } " h = self . _hash ( virtual_key ) self . ring [ h ] = node bisect . insort ( self . sorted_keys , h ) def remove_node ( self , node : str ): for i in range ( self . replicas ): virtual_key = f " { node } :vnode: { i } " h = self . _hash ( virtual_key ) del self . ring [ h ] idx = bisect . bisect_left ( self . sorted_keys , h ) self . sorted_keys . pop ( idx ) def get_node ( self , key : str ) -> str : if not self . ring : raise ValueError ( " Ring is empty " ) h = self . _hash

2026-06-14 原文 →
AI 资讯

Struct Embedding in Go: Composition That Bites When You Reach for Inheritance

Book: The Complete Guide to Go Programming Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You come to Go from a language with classes. You see struct embedding for the first time, and it reads like inheritance. A field with no name, methods that "carry over" to the outer type, a base struct that your type extends. So you write code the way you always have, and most of it works. Then a method does something you did not ask for, a type satisfies an interface you never meant to implement, or two embedded types fight over a name and the compiler shrugs until the exact line that calls it. Embedding is not inheritance. It is composition with a syntax that promotes methods and fields up one level. Once you hold that distinction, the surprises stop being surprises. Here is where they come from. Embedding promotes, it does not subclass Write an embedded field by giving a type with no field name: type Engine struct { Horsepower int } func ( e Engine ) Start () string { return "vroom" } type Car struct { Engine // embedded Brand string } Car now has a Start method and a Horsepower field, both promoted from Engine . You can write car.Start() and car.Horsepower as if they were declared on Car . car := Car { Engine : Engine { Horsepower : 300 }, Brand : "Fiat" } fmt . Println ( car . Start ()) // vroom fmt . Println ( car . Horsepower ) // 300 This is where the inheritance illusion starts. car.Start() is sugar. The compiler rewrites it to car.Engine.Start() . The receiver of Start is still an Engine , never a Car . There is no base class, no super , no virtual dispatch. Engine does not know Car exists. That last point is the one that bites. A promoted method runs against the embedded value, not the outer struct. The method that ignores the outer struct Say you want a stringer on the embe

2026-06-14 原文 →
AI 资讯

defer in Loops: The Resource Leak Go Still Lets You Write

Book: The Complete Guide to Go Programming Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You wrote a function that walks a directory and reads every file. It opened cleanly in review. It passed tests on a fixture folder with three files. Then a customer pointed it at a folder with 20,000 files, and the logs filled with: open /data/batch/img-08431.png: too many open files The code never closed anything early. It deferred every close. And that is exactly the problem. defer runs at function return, not end of iteration defer schedules a call to run when the surrounding function returns. Not when the current block ends. Not when the loop iteration ends. When the function returns. Most of the time that distinction does not matter, because most deferred calls live in short functions that return quickly. Put a defer inside a for loop, though, and every iteration adds one more deferred call to a stack that does not unwind until the whole loop is done and the function exits. Here is the version that ships: func processFiles ( paths [] string ) error { for _ , p := range paths { f , err := os . Open ( p ) if err != nil { return err } defer f . Close () // runs at RETURN, not here if err := handle ( f ); err != nil { return err } } return nil } Read it the way the language reads it. On the first iteration, os.Open returns a file handle and you defer its close. On the second iteration, another handle, another deferred close. By the time the loop has touched 20,000 files, you are holding 20,000 open descriptors, and not one of them closes until processFiles returns. Your process has a file-descriptor limit. On Linux the soft default is often 1024. You blow through it somewhere around the 1024th file, and the error you get back says nothing about defer . It says too many open files , wh

2026-06-14 原文 →
AI 资讯

Query Objects in PHP: Rich Filtering Without Leaking SQL Into the Domain

Book: Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You ship a list endpoint. GET /orders . It returns the customer's orders, newest first. Clean. Then product wants a status filter. Then a date range. Then "only orders over 100 euros". Then pagination. Then sort by total, descending. Six months later the controller signature reads like a tax form, and the repository method that backs it is findByCustomerAndStatusAndMinTotalBetweenDatesOrderedBy(...) with nine parameters, three of them nullable. So you "fix" it. You let the caller pass a Doctrine QueryBuilder into the repository. Or worse: the use case starts assembling WHERE clauses as strings because that was the fastest way to add the next filter on a Friday. Now your application layer knows about table aliases and SQL operators. The domain speaks SQL, and the whole point of having a repository interface is gone. There is a shape that holds: a query object the domain builds, and an adapter that translates it into SQL. The caller describes what it wants in domain terms. The adapter decides how to fetch it. The leak, concretely Here is the version that grows out of control. Every new filter is another nullable parameter. public function search ( ?string $customerId , ?string $status , ?DateTimeImmutable $from , ?DateTimeImmutable $to , ?int $minTotalCents , string $sortBy = 'placedAt' , string $direction = 'DESC' , int $page = 1 , int $perPage = 20 , ): array ; Nine parameters, half of them nullable, two of them ( sortBy , direction ) carrying raw column names that map straight to SQL. Add a filter and the signature grows again. Every caller has to remember positional order. And $sortBy is a column name leaking through the port: t

2026-06-14 原文 →