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

标签:#backend

找到 212 篇相关文章

AI 资讯

OAuth Failure Recovery: Why I Choose Safe Retries for Authorization and Callback Steps

Short answer: Retry the transport operation, never the OAuth meaning: keep one durable authorization attempt, accept its callback once, and make every downstream effect replayable from recorded state. For a B2B SaaS account-deletion flow, I would block new sessions before attempting remote cleanup, because deleting data while a surviving session can still act is the more dangerous ordering. That is the architecture decision. It treats a timeout as missing knowledge, not proof of failure. A callback may have committed even when the browser received no response; a token exchange may have reached the other side even when the connection closed; an account deletion may be retried by a worker after its first lease expires. The recovery design must therefore answer a narrow question at each boundary: do we know the operation did not happen, do we know it happened, or is the result still unknown? What must remain true during OAuth failure recovery? The first invariant is that an authorization attempt has one identity independent of any HTTP request. Store an opaque flow identifier, the expected callback state, the account or tenant context, a creation time, an expiry, and a small state machine such as pending , exchanging , succeeded , or failed . Don't let a browser refresh create a second logical attempt merely because it creates a second request. The second invariant is single consumption. An authorization code and its state belong to one attempt; the callback handler must atomically claim that attempt before triggering side effects. A duplicate callback should read the previously recorded outcome and return the same application-level destination. It must not provision the user again, issue another internal session, or append a second audit event that claims a second login. Exactly once is the goal, but HTTP cannot promise it by itself, so I use an exactly-once mindset at the business boundary: an atomic database transition establishes who owns the work, unique constrain

2026-08-29 原文 →
AI 资讯

PostgreSQL Multi-Tenancy: Isolation That Survives a Growing Team

Startups building B2B products reach for multi-tenancy in PostgreSQL the same way on day one: one shared database, one set of tables, and a tenant_id column marking who owns each row. That is the correct call, and it stays correct for a long time. However, when that column is enforced by application code rather than by the database, a single forgotten predicate stops being a bug and becomes a disclosure event, and a disclosure event is one of the very few engineering failures that lands straight on your balance sheet as stalled enterprise deals, an unplanned legal bill, and a security review you can no longer pass. By understanding what multi-tenancy actually guarantees, which isolation model fits your stage, and how Row-Level Security moves that guarantee out of your codebase, startup CTOs and Fractional CTOs can make the tenant boundary hold without slowing the team down. (If you want to skip the theory, jump straight to the connection pooler trap that switches Row-Level Security off in production, what it costs in query performance, or when it is genuinely time to leave the shared schema.) Because "enforced by application code" means something very specific in practice. It means a promise that everyone will remember to filter on tenant_id , and that promise is the single most expensive line of undocumented policy in your entire codebase, because it holds perfectly for about fourteen months, right up until the afternoon a tired engineer ships a reporting endpoint that joins four tables and forgets the predicate on exactly one of them, and then a customer opens a dashboard and sees somebody else's invoices. That is not a bug. A bug is something you fix on Monday. A cross-tenant data leak is a disclosure event, which means legal gets involved, your enterprise prospects get an email from their own security team, and the deal that was supposed to close your Series A quietly moves to next quarter and then to never. The uncomfortable part is that this is not a story abo

2026-08-28 原文 →
AI 资讯

Webhooks vs Polling: Why Real-Time Integrations Matter in 2026

Webhooks vs Polling: Why Real-Time Integrations Matter in 2026 In modern software, knowing that something happened is often just as important as knowing what happened. A customer completes a payment. An order changes from pending to shipped. A user creates an account. A GitHub pull request is opened. A subscription is renewed. An AI workflow needs to start processing a new request. The question is simple: How does your application know that something changed? For years, developers have relied on two common approaches: polling and webhooks. Both solve the same fundamental problem—keeping systems synchronized—but they do it in completely different ways. Polling repeatedly asks an API whether something has changed. Webhooks allow the external system to notify your application when something actually happens. That difference can have a major impact on performance, scalability, API usage, responsiveness, reliability, and overall system architecture. And as applications become increasingly connected in 2026, understanding when to use each approach is more important than ever. What Is Polling? Polling is the traditional approach to checking for changes. Your application periodically sends a request to another system: “Has anything changed?” For example, imagine an e-commerce application that needs to know when an order has been paid. It might call an API every 30 seconds: GET /orders/12345 The response might say: status: pending Thirty seconds later, the application asks again. Then again. And again. Eventually: status: paid The application finally discovers that the payment has been completed. The basic workflow looks like this: Application → API → “Anything new?” API → Application → “No.” Thirty seconds later: Application → API → “Anything new?” API → Application → “No.” Eventually: Application → API → “Anything new?” API → Application → “Yes, the order has been paid.” The approach is straightforward and easy to understand. But there is a problem. Most of those requests

2026-08-28 原文 →
AI 资讯

From SOLID to Composition, Dependency Injection, and IoC: How Angular, Spring, and Node.js Differ

When learning Angular, Spring, and Node.js, I often came across terms like SOLID, Dependency Injection (DI), Inversion of Control (IoC), IoC Container, and Composition . At first, these concepts can feel like they are all the same thing. They are not. The key realization is: SOLID is about how we design software. Composition is about how we build larger systems from smaller pieces. Dependency Injection is a technique for providing those pieces. IoC containers automate that process. Understanding this relationship makes Angular, Spring, and Node.js architectures much easier to reason about. 1. SOLID Is a Design Principle, Not a Framework Feature SOLID is a collection of software design principles. For example, Single Responsibility Principle (SRP) says that a component should have a focused responsibility. Instead of having one class responsible for HTTP handling, database access, validation, email, and payment processing, we can separate those responsibilities: Controller ↓ Service ↓ Repository ↓ Database Each part has a focused job. Similarly, the Open/Closed Principle (OCP) encourages us to design components that can be extended without constantly modifying their existing implementation. These principles don't require Angular, Spring, or an IoC container. You can follow SOLID in plain JavaScript. 2. Composition Is the Bigger Idea Composition means: Build a larger behavior by combining smaller, focused pieces. This works in both functional and object-oriented programming. In functional programming: function A ↓ function B ↓ function C A larger function can be created by composing smaller functions. In object-oriented programming: OrderService │ ├── PaymentService └── EmailService OrderService is composed using other objects. The important relationship is often: HAS-A rather than IS-A For example: OrderService HAS-A PaymentService rather than: OrderService IS-A PaymentService This is one reason composition is often preferred over deep inheritance hierarchies. 3. Dep

2026-08-27 原文 →
AI 资讯

Frontend Backend Correlated Logging: Browser Fetch Request IDs and Server Logs

Short answer: give each browser fetch a request ID, carry it to the backend in a standard HTTP header, and emit that same ID in structured logs on both sides. Keep the pricing decision itself behind a flag with an explicit evaluation ID, so a rollback can be verified instead of guessed. The browser is the first audit surface Rolling out a new pricing rule in an edtech app sounds like a feature-flag task. Operationally, it is a tracing problem with money attached. A student sees a price in the browser, the frontend calls the checkout backend, and the backend evaluates a flag before writing an order. When those events cannot be joined, a rollback turns into a debate about which request produced which price. I've been paged for missed jobs and duplicate deliveries. The same failure pattern appears here: a dashboard says the system is healthy, but the individual request that matters is hard to reconstruct. A request ID doesn't prove that a price was correct. It makes the evidence joinable. The smallest useful contract is straightforward: The browser creates a non-secret request ID for each outbound fetch. The ID travels in X-Request-ID (or the equivalent header chosen by the team). The server validates or replaces malformed values, then logs the accepted value. Every log record for the request includes the ID, route, outcome, and duration. A separate flag-evaluation ID identifies the pricing decision and its rule version. Don't put a user email, token, or price in the request ID. It's a correlation key, not an authorization mechanism or a business record. How should frontend and backend logs correlate a browser fetch request ID? The browser and server need a shared boundary, not a shared logging library. For a JavaScript or Node.js application, the fetch wrapper should generate an ID before sending the request and attach it to the headers. The Node.js service should read that header at the HTTP edge, bind it to request context, and include it in every subsequent log eve

2026-08-27 原文 →
AI 资讯

NET Framework Essentials: Web Development Simplified

Your backend framework will outlive your current team. Choose one that the next team can still navigate — here's why .NET has been that framework for Netflix, GitHub, and Stack Overflow for over two decades. Summary Twenty-three years. That's how long .NET has been running in production. Most frameworks from that era got abandoned, forked beyond recognition, or replaced entirely — .NET kept showing up. Netflix still uses it. GitHub uses it. Stack Overflow, which has probably saved more developer careers than any single resource on the internet, runs on ASP.NET. None of these teams are using it out of inertia. They're using it because it works under conditions that expose every weakness in a poorly designed system. This article gets into how .NET actually works, what it gives teams day-to-day, and whether it makes sense for what you're building now. Key Takeaways: One codebase, five platforms — Windows, macOS, Linux, Android, iOS. No rewrites, no platform-specific forks. Three languages, one project — C#, F#, and Visual Basic coexist without forcing a rewrite. The performance tooling ships with it — JIT compiler, AOT compiler, CLR memory management, Garbage Collector. All out of the box. Why Is .NET Still Around? Honestly, this question is worth sitting with for a second — because in software, most things don't survive twenty years. They solve the problem of the moment, get widely adopted before anyone finds the sharp edges, and then get quietly replaced when something newer comes along and the migration pain seems worth it. .NET didn't go that way. Some of that is Microsoft backing — resources, long-term support commitments, a developer community that doesn't dissolve when priorities shift. But backing alone doesn't explain it. Plenty of well-resourced frameworks have died. What actually kept .NET alive is that the foundational architecture held up. The cross-platform capability wasn't duct-taped on in 2020 because everyone suddenly cared about Linux. It was in the

2026-08-26 原文 →
AI 资讯

Adding OpenAPI Support to Mummy, a Nim HTTP Framework

Nim doesn't have a lot of options for building HTTP APIs with the kind of batteries-included developer experience you get in frameworks like FastAPI or Express with Swagger middleware. mummy is a fast, solid HTTP/WebSocket server library for Nim (my fork with the additions below is at github.com/isaiahpeter/mummy ) — but out of the box, it doesn't generate OpenAPI specs, validate request bodies, or give you typed path parameters. So I forked it and added those. This post walks through what I built, why, and what I learned extending an existing Nim library instead of starting from scratch. Why mummy, and why OpenAPI I wanted a Nim backend for a few projects (a contact-form API, a todo API demo) and kept missing three things I'd take for granted in other ecosystems: Auto-generated API docs — a /docs endpoint you can actually hand to someone, generated from your routes instead of hand-written. Typed path parameters — pulling id out of /users/{id} as an int without manual parsing and error handling in every handler. Request validation — rejecting a bad JSON body before it reaches your handler logic, with a schema to back it up. mummy is fast and minimal by design, which is exactly why it was worth extending rather than replacing. What I added OpenAPI spec generation. I added openapi_schema.nim and openapi_router.nim , which let you wrap routes in an OpenApiRouter and attach a summary, tags, and a response schema via schemaOf . The router serves both /openapi.json and a browsable /docs page generated from your actual route definitions — so the docs can't drift out of sync with the code the way hand-written API docs do. Typed path parameters. pathParam[T](request, "id") pulls a path segment and parses it as the type you ask for, with a clean 400 response if parsing fails. One gotcha worth flagging if you try this yourself: in this Nim version, the generic dot-call form ( request.pathParam[int]("id") ) doesn't parse — you have to call it as pathParam[int](request, "id") in

2026-08-26 原文 →
AI 资讯

React Form Backends Compared: Serverless Functions vs. Form-as-a-Service

React Form Backends Compared: Serverless Functions vs. Form-as-a-Service React makes building a form straightforward. What happens after onSubmit is a different question: you still need somewhere to validate, process, store, or forward the submission. Two common approaches are writing a serverless function yourself or using a hosted form backend such as onsubmit.dev (form backend). This article compares the two, using Vercel/Netlify-style functions for the DIY approach and onsubmit.dev with its React integration as the managed example. The basic problem Imagine a typical contact form: function ContactForm () { return ( < form > < input name = "email" type = "email" required /> < textarea name = "message" required /> < button type = "submit" > Send </ button > </ form > ); } The React component is only the UI. A real application usually needs backend behavior too: accepting the HTTP request validating and sanitizing input handling errors preventing abuse or spam delivering or storing the submission keeping credentials and other secrets off the client There are two broad ways to get that backend. Option 1: Build a serverless function With platforms such as Vercel and Netlify, you can create an HTTP function alongside your application and have your React form submit to it. Conceptually, the architecture looks like this: React form | v Your serverless function | +--> validation +--> email provider +--> database +--> other services The main advantage is control. Your function owns the request lifecycle, so you decide precisely how data is validated, transformed, authenticated, stored, and forwarded. If a submission needs to update PostgreSQL, call an internal API, enqueue a job, and return application-specific data, a custom backend is usually the natural solution. Serverless functions can also reduce product-level vendor lock-in. Although platforms have their own deployment conventions, HTTP handlers and their business logic are generally portable with some work. The tr

2026-08-25 原文 →
AI 资讯

A New Way to Build Aggregation Pipelines in Go

This article was written by Lin Borland Aggregation pipelines are one of the most powerful tools in MongoDB. They let you filter, reshape, compute, and group documents in a single query. In practice, the aggregation framework feels almost like a language of its own. With its combination of stages, expressions, and operators, you can describe everything from straightforward filtering to sophisticated transformation logic. This expressive power is what makes aggregation pipelines so useful, and is also why they have a learning curve associated with them. If you’ve worked with MongoDB in Go, you may know that the existing syntax for writing pipelines in Go can be cumbersome to work with. This is especially true when a pipeline includes several stages, repeated computed logic, or deeply nested expressions. In these cases, both readability and writability may begin to suffer. There’s a need for a more Go-native way to build aggregation pipelines. This is why we’re introducing a new approach: an experimental aggregation builder in Go. In this article, we’ll compare the traditional and new approaches, then go through an example. The traditional BSON-based approach Today, if you want to build an aggregation pipeline with the Go driver, you typically do it with bson.D, bson.A, and mongo.Pipeline. While this approach is flexible, it can be hard to spot small mistakes. Let’s use a simple example from the sample_mflix.movies collection. Suppose we want to find movies released after the year 2000. Here’s a pipeline that demonstrates how easy it can be to get the shape wrong: mongo . Pipeline { bson . D {{ Key : "$match" , Value : bson . E { Key : "$gte" , Value : bson . E { Key : "$year" , Value : 2000 }}}}} At a glance, the mistake might not be obvious. The document is valid BSON, but the pipeline uses “bson.E” instead of “bson.D” for some values, resulting in a pipeline that returns zero results. If we try to fix the nesting, we can still end up with a pipeline that is structu

2026-08-25 原文 →
AI 资讯

The Upload Succeeded, the Record Did Not

Originally published on hexisteme notes . I built a YouTube upload stage for a video pipeline, and the flow looked clean enough on paper: start a resumable session, PUT the file, get back a video ID, verify the upload actually landed the way it was supposed to, then write a local record marking the episode as uploaded. Four steps, each one depending on the last. It was the dependency between the last two that turned out to be the problem. The sequence, and where it breaks Verification here means re-querying the video through videos.list after the upload finishes, to confirm the visibility wasn't silently demoted, the upload wasn't rejected, and the metadata actually propagated. That's a reasonable thing to check — YouTube's upload API can report success at the transport layer while the platform-side processing does something you didn't ask for. But if that verification call raises, the exception propagates straight up, and the local record — a JSON file I'll call upload.json — never gets written. Not "gets written with an error flag." Never written, period. By the time that exception fires, though, the video already exists on YouTube. The PUT succeeded. The video ID is real. There's a public (or not-quite-public) video sitting on the channel, and there is exactly nothing on disk that knows about it. Run the same command again after that, and the guard that's supposed to answer "have I already uploaded this?" — a check for whether upload.json exists — sails right through, because it doesn't exist. The result isn't a retry. It's a second, completely independent upload of the same video. What "retries don't duplicate" actually meant The module's docstring said retries don't create duplicate videos. That line wasn't wrong, exactly — it was scoped narrower than it read. It was true for retries inside the low-level file-PUT function, which reuses the same resumable session URI on retry, so transport-layer hiccups during the upload itself are genuinely safe to retry. What

2026-08-25 原文 →
AI 资讯

Node.js Express vs. Python FastAPI: Which Should You Choose in 2026?

Node.js Express vs. Python FastAPI: The Definitive Guide for Choosing Your Next Backend Choosing a backend framework used to be simple. If you liked JavaScript, you built with Express. If you liked Python, you went with Flask or Django. But the landscape has fundamentally shifted. With the explosion of AI, machine learning, and strict type safety, Python FastAPI has emerged as a powerhouse alternative to the traditional JavaScript runtime. Meanwhile, Node.js Express remains the unopinionated king of the enterprise web. If you are starting a new project today, which one should you choose? Let’s break down the technical trade-offs, developer experience, and code structures of both frameworks. 🚀 The Core Philosophy Node.js Express: The Minimalist Canvas Express is a minimalist, unopinionated framework. It doesn't care how you structure your folders, how you validate data, or how you handle errors. It gives you a robust set of HTTP tools and steps out of your way. The Catch: You have to build or install your own solutions for data validation, ORM mapping, and API documentation. Python FastAPI: The Automated Powerhouse FastAPI is built on modern Python 3.8+ features like type hints and asynchronous ASGI (asyncio). It is highly opinionated about data handling, leveraging Pydantic to automate input validation and schema serialization. The Catch: It forces you into a specific way of handling data types from day one, which can feel restrictive if you prefer absolute freedom. 📊 Feature Breakdown Feature Node.js Express Python FastAPI Language JavaScript / TypeScript Python Data Validation Manual / Third-Party (Zod, Joi) Native via Pydantic API Docs Manual Setup (Swagger UI plugin) Automatic (Interactive Swagger UI & ReDoc) Best For Real-time I/O, WebSockets, Full-stack JS AI/ML APIs, Data pipelines, Type-safe apps 🛠️ Code Comparison: Creating a Validated POST Route Let’s look at how both frameworks handle a common task: creating a POST endpoint that accepts an item, validates

2026-08-24 原文 →
AI 资讯

EF Core bugs that look like correct code

Most EF Core bugs I've seen in production aren't from bad code. They're from code that looks right. It compiles, it passes review, it works fine locally against a database with twelve rows in it. Then it hits a table with five thousand rows, or a second replica, or a request that gets cancelled halfway through, and it falls over in a way nobody wrote a test for. None of the mistakes below are exotic. They're the default behavior of EF Core when you don't opt out of it, or the default behavior of a deployment when nobody thought about what "five pods start at the same time" actually means. Here's the setup I use and the list of ways it goes wrong if you skip a step. The entity namespace Sample.Domain.Posts ; public sealed class Post { public Guid Id { get ; private set ; } = Guid . CreateVersion7 (); // sequential → index-friendly public required string Title { get ; set ; } public required string Slug { get ; init ; } public string Body { get ; set ; } = string . Empty ; public DateTimeOffset ? PublishedAt { get ; private set ; } public Guid AuthorId { get ; init ; } public uint RowVersion { get ; set ; } // optimistic concurrency token public void Publish ( TimeProvider clock ) { if ( PublishedAt is not null ) throw new DomainException ( "Post is already published." ); PublishedAt = clock . GetUtcNow (); } } Two things here that are easy to skip and annoying to retrofit later. Timestamps are stored as UTC ( DateTimeOffset ), rendered in the user's timezone only at the edge — I do the same thing on ProcessHub, storing everything UTC and rendering in Asia/Tehran, because "what timezone is this in" is a much worse question to answer after the data already exists in three different formats. Second: the clock comes in as TimeProvider , not a call to DateTime.UtcNow buried inside the method. It's a small thing, but it's the difference between a test that can assert "publishing sets the timestamp to exactly this value" and a test that has to accept "sometime around now."

2026-08-24 原文 →
AI 资讯

Too Many Req: A Bucket List Guide to Building a Rate Limiter

Hello, I'm Maneshwar. I'm building git-lrc, a Micro AI code reviewer that runs on every commit. It is free and source-available on Github. Star git-lrc to help devs discover the project. Do give it a try and share your feedback. Every serious API will eventually tell you to sit down and be quiet. Hammer GitHub, Stripe, or AWS a little too eagerly and your requests start bouncing back with a polite but firm 429 . I always found that fascinating, so let's build the thing that says no. By the end of this post we'll have designed a rate limiter that actually holds up when you put it in front of real traffic, and I promise to only make a reasonable number of bucket puns along the way. A rate limiter does one job: it decides how many requests a client is allowed to make in a given window of time. It protects your system from getting flattened, and it keeps one greedy user from eating everyone else's lunch. Simple idea. Surprisingly spicy implementation. Let's build it up piece by piece, the way you'd actually reason through it in an interview or a design doc. First, what are we even building? Before writing a single line, let's agree on what "good" looks like. Here's my wishlist: Configurable limits. Something like "100 requests per minute per user." The rules should not be hardcoded, because free users and premium users deserve different amounts of pain. Honest rejections. When someone goes over, we return HTTP 429 Too Many Requests and include helpful headers telling them how many requests they have left and when the window resets. No mystery. Barely-there latency. This check runs on every single request , so it has to be fast. Let's aim for under 3ms at P95. If your rate limiter is slow, congratulations, you built a second bottleneck. Highly available and shared. Multiple servers need to agree on the same counts. More on why that word "shared" is doing a lot of heavy lifting later. Cool. Now let's start naive and let reality punch us in the face a few times. Attempt 1:

2026-08-24 原文 →
AI 资讯

Bulletproofing AI Agents: How to Prevent $2,000 Infinite API Loops

Implement multi-layer circuit breakers, payload hashing, and financial cutoffs before an autonomous agent drains your backend. The Bottleneck in Production Autonomous AI agents running in tool-use loops fail unpredictably. When an LLM encounters an unexpected schema, a transient network error, or an ambiguous prompt, it often enters a hallucinated retry storm. In standard web apps, a runaway loop hits a rate limit or returns a 500 Internal Server Error . In agentic architectures, an unconstrained ReAct loop executes external API calls continuously, burning tokens, exhausting upstream quotas, and running up massive cloud bills in minutes. Here is the anti-pattern running in far too many codebases: # Anti-pattern: Unbounded autonomous agent loop while not task_complete : action = llm . decide_action ( state ) result = external_api . call ( action . endpoint , action . params ) state = update_state ( result ) If the LLM fails to transition state due to an unparseable response, this loop runs indefinitely. Cloud providers do not issue refunds for self-inflicted API usage. The System Architecture & Fix To make AI agent tool execution production-safe, never allow direct API calls from agent code. Route every external request through an isolated API Safety Wrapper implementing three distinct layers of defense: Deterministic Request Firewall: A hard cap on execution count per task session (Time-To-Live counter). Sliding-Window Loop Detector: Hashing outgoing request payloads to catch repetitive or oscillating tool invocations. Financial Kill Switch: A pre-flight budget validator that cuts credentials immediately if projected cost exceeds session limits. [ AI Agent Engine ] │ ▼ [ API Safety Wrapper ] ├── 1. Call Counter Check (Limit < N) ├── 2. Hash Duplicate Detector (Window: last 3 calls) └── 3. Pre-flight Cost Estimator (Budget < Limit) │ ┌────┴──────────────────────────┐ [ Passed ] [ Tripped ] │ │ ▼ ▼ [ External Upstream API ] [ Emergency Kill Switch ] (Revoke Token & Ab

2026-08-22 原文 →
AI 资讯

Seven Mobile OTP Login Invariants for Backend APIs and Abuse Prevention

Short answer: model each SMS OTP as an auditable challenge that can be consumed once, and make the server—not the mobile screen—the authority for expiry, autofill acceptance, repeat-request limits, and recipient suppression. Those decisions belong in the security contract before a messaging adapter is selected. The concrete problem is deceptively small: a mobile user asks for a code, the app receives a text, and the user signs in. In production, the same endpoint is also a spending endpoint, a privacy boundary, and a fraud signal. A duplicate tap, a delayed carrier message, or a recycled phone number can turn a pleasant login flow into an account-enumeration or SMS-bombing incident. I approach this like a ledger. Every state transition needs an idempotency key, an audit record, and a clear owner. Seven invariants keep the design reviewable. Stop. Consent, retention, and privacy records The server creates a challenge with a random, short-lived code, stores only a salted hash, and binds the challenge to a normalized recipient plus a login intent. The client receives an opaque challenge identifier; it never decides whether a code is valid. Verification consumes the challenge atomically, so two concurrent requests cannot both win. A resend is a new delivery attempt on the same login intent, subject to a cooldown and a rolling budget. It must not silently invalidate a code that is already in transit unless the product explicitly documents that behavior. Suppression is checked before dispatch and again when delivery feedback is ingested. That second check matters for bounces, reassigned numbers, and manually blocked recipients. Option Strength Cost or boundary One service owns challenge and delivery state Simple audit trail and exactly-once verification Requires a durable store and transactional writes Separate identity and messaging services Teams can deploy independently Correlation IDs and replay rules cross a network boundary Client-generated code or expiry Fast proto

2026-08-22 原文 →
AI 资讯

WebMCP Agentic Web: Debugging 2‑Second Latency Spikes

webmcp agentic web: Why Backend Engineers Must Rethink Their Architecture Quick Answer webmcp agentic web: Agentic web workloads over MCP require stateless gateways, distributed context stores, prompt caching, and fine‑grained telemetry to keep latency below 350 ms and cost under control. Latency and State in Multi‑Agent LLMs When a Multi‑Agent System talks to an LLM over the Model Context Protocol (MCP) , the assumptions that hold for CRUD REST APIs break apart. A 200‑ms timeout that covers a simple GET request now collapses into a 2‑second latency spike because each tool call injects a new sub‑prompt, inflates the token budget, and forces the backend to stitch together dozens of partial contexts. In the field, the LLM behaves like a stateful, high‑throughput service that must be orchestrated, not a stateless function. Real‑World Example Consider a U.S. e‑commerce platform that needs to serve 12 k concurrent shopping sessions. Each session spawns up to five agents (pricing, inventory, recommendation, fraud, checkout). The platform’s existing micro‑service stack was built for single‑shot CRUD calls; when the agentic layer was added, the following issues surfaced: Context drift: stale prompts silently degraded recommendation quality. Token explosion: every tool call added 200–300 tokens, pushing the total payload past 8 k tokens. Throughput hit: the MCP service was throttled by Azure OpenAI’s per‑deployment request rate limits. After re‑architecting to a stateless MCP gateway backed by a distributed context store, the platform maintained 99th‑percentile latency under 350 ms even during a Black Friday surge. Trade‑Offs Aspect Option A Option B When to choose Context Storage Redis Cluster (in‑memory, low latency) Cosmos DB (strong consistency, global replication) Redis for ultra‑low latency, Cosmos for compliance or multi‑region writes Prompt Caching Enable KV‑cache on Azure OpenAI Re‑send system prompt on every request Enable when prompt size >20% of total token budge

2026-08-20 原文 →
AI 资讯

Physical Server vs Cloud Server: Which Infrastructure Makes More Sense?

When building an application, we usually focus on the frontend, backend, APIs, and database. But there is another important question: Where should the application actually run? Two common approaches are physical servers and cloud/virtual servers. Understanding the difference is important because infrastructure decisions affect scalability, availability, security, maintenance, and cost. What Is a Server? A server is a computer system that runs applications, processes requests, communicates with databases, and provides information to users. A typical request might look like: User → Internet → Application Server → Backend → Database → Response Depending on the application, the server may handle authentication, APIs, user data, file processing, notifications, and other backend operations. In simple terms, the server provides the execution environment behind the application. Physical Server: More Control, Less Flexibility A physical server is a dedicated machine used to run applications. For example: 16 CPU cores + 64 GB RAM + 2 TB SSD Advantages: • Dedicated hardware • Predictable performance • Greater hardware-level control • Suitable for stable workloads Limitations: • Higher initial investment • Hardware maintenance • Hardware failures can cause downtime • Scaling requires additional or upgraded hardware If an application suddenly grows beyond the capacity of the machine, increasing capacity may require purchasing and configuring new hardware. Cloud / Virtual Server: Infrastructure That Can Adapt A cloud server is a virtual server running on physical infrastructure inside a cloud data center. For example: 4 vCPU + 16 GB RAM + SSD Instead of purchasing the entire physical machine, resources can be provisioned according to the application's requirements. Cloud environments also provide different scaling approaches. Scale Up: Increase the resources of an existing server. 4 vCPU → 8 vCPU → 16 vCPU Scale Out: Add additional application instances. Application Server 1 + Ap

2026-08-20 原文 →
AI 资讯

How to Stop Your Discord Bot From Sleeping on Render's Free Tier

A step-by-step tutorial to stop a discord bot from sleeping on Render's free tier — the real cause, the fix, and a working code example. How to Stop Your Discord Bot From Sleeping on Render's Free Tier You've deployed your Discord bot to Render's free tier, it worked for a bit, and now it's going offline — sometimes after a few minutes, sometimes randomly. This is one of the most common issues developers hit deploying a bot for the first time, and it has a specific, well-understood cause and a fix you can ship in under ten minutes. Table of Contents Why This Happens on Render Specifically Confirming This Is Your Actual Problem Step 1: Install StayPresent Step 2: Wrap Your Bot's Entry Point Step 3: Read Render's Assigned Port Step 4: Set Your Render Start Command Step 5 (Optional): Prevent Inactivity Sleep Specifically Verifying It Worked FAQs Conclusion Why This Happens on Render Specifically Render's free-tier web services are checked for health over HTTP, and free services also spin down after a period without incoming traffic. A discord.py bot connects outward to Discord's gateway — it never opens an HTTP port of its own, which is completely normal bot behavior. Render's health checker, seeing nothing respond on the expected port, has no way to know the bot is actually working fine internally. It just sees silence, and reacts accordingly. Confirming This Is Your Actual Problem If your bot's entry point goes straight into bot.run(TOKEN) with nothing else, and Render's dashboard shows the deployment as unhealthy or repeatedly restarting with no matching error in your bot's own logs, this is almost certainly it. Step 1: Install StayPresent pip install staypresent[prod] Add it to your requirements.txt as well: staypresent[prod] discord.py Step 2: Wrap Your Bot's Entry Point Keep your existing bot code in bot.py completely unchanged. Create a new main.py : import os import staypresent staypresent . web . json ({ " status " : " running " }) staypresent . run ( " bot.py

2026-08-20 原文 →
开发者

Implementing IN statements using JooqTemplate

@Service public class SimpleUserService { @Autowired private JooqTemplate jt ; public List < user > selectUserInDept ( UserParam param ) { //If deptIDs==null or deptIDs. isEmpty automatically ignores this query condition // SELECT * FROM user_table WHERE name LIKE '%?%' AND dept_id IN (?,?...); return jt . queryv ( "user_table" , User . class , "name%" , param . getName (), "dept_id:in" , param . getDeptIds ()); } public List < user > selectUserNotInDept ( UserParam param ) { // SELECT * FROM user_table WHERE name LIKE '%?%' AND dept_id NOT IN (?,?...); return jt . queryv ( "user_table" , User . class , "name%" , param . getName (), "dept_id:notin" , param . getDeptIds ()); } }

2026-08-20 原文 →
AI 资讯

Transactional Email Warmup Explained — 5 Steps for Deliverability and Volume Ramping

Short answer: use a dedicated sending domain, let real transactional demand set the pace of a gradual ramp, and make every receipt request idempotent and auditable before tuning volume. The least complex reliable design is a payment-settled event feeding an outbox, one delivery worker, and a feedback ledger; a synthetic warmup stream adds traffic but does not prove that customers want or engage with the mail. Proof first. Start with the bill because retention can quietly cost more than the send path. Model monthly storage as messages per day × retained bytes per message × retention days , then measure each term rather than guessing. The retained bytes often include rendered bodies, provider responses, event payloads, and repeated recipient data. Sending volume is constrained by the business, but body duplication and retention are design choices. Store one immutable template version, a compact render-input record, message hashes, timestamps, and normalized delivery events; expire full rendered bodies on a declared schedule. This changes the growing term from repeated message bodies to small audit records. The deliberate loss is important: after a body expires, an operator can prove which template and inputs were used, but may be unable to reproduce byte-for-byte output if an external dependency or template engine has changed. Compliance, legal hold, and dispute requirements must therefore set retention before an engineer optimizes it. There is no universal number. How should a dedicated domain warmup plan ramp transactional email sending volume? Treat warmup as controlled production exposure, not a calendar ritual. A new dedicated domain starts without the history of an established stream, while an order receipt is time-sensitive and cannot be withheld merely to preserve a tidy ramp chart. The plan needs two lanes: a conservative new-domain lane for eligible traffic and an established fallback lane that remains available until the new lane has enough observed outcome

2026-08-19 原文 →