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

标签:#backend

找到 94 篇相关文章

AI 资讯

Persisting One Aggregate Across Multiple Tables, ORM-Agnostic

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 have an Order . It owns line items and a shipping address. In the database that is three tables: orders , order_items , order_addresses . The aggregate is one thing in the domain and three rows-with-children in storage. Now look at what most codebases do with that. The service loads the order, loops the items, saves each one in its own statement. Halfway through, a unique-constraint violation throws. The order header is already committed. Two items are in. One address is missing. You have a row in orders that no part of the system considers valid, and no single place to point at when you ask how it got there. The aggregate is supposed to be a consistency boundary. Saving its parts in separate, independently-committing operations breaks that boundary on the way to disk. This post is about closing it: one repository, one transactional save across every table, and a read path that rebuilds the whole object from rows without leaking the ORM into the domain. The aggregate the domain sees The domain class has no idea it lives in three tables. It holds its children directly and guards their invariants. <?php declare ( strict_types = 1 ); namespace App\Domain\Order ; use App\Domain\Shared\Money ; final class Order { /** @var list<LineItem> */ private array $items ; private function __construct ( private readonly OrderId $id , private readonly CustomerId $customerId , array $items , private Address $shipTo , private OrderStatus $status , ) { if ( $items === []) { throw new InvalidOrder ( 'order needs an item' ); } $this -> items = array_values ( $items ); } public static function place ( OrderId $id , CustomerId $customerId , array $it

2026-06-14 原文 →
开发者

I Spent 30 Days Building a Complete Node.js Learning Path (Free for Everyone)

What This Repository Is A complete, structured, beginner-friendly Node.js learning path. 30 sessions. Each session has Clear learning objectives Step-by-step explanations Working code examples Practice exercises Interview questions Summary of key points No fluff. No assumptions. Just code. The Complete Curriculum Phase 1 - Node.js Fundamentals (Sessions 1-5) Session Topic What You Will Build 01 Introduction to Node.js Your first Node.js program 02 Project Setup and npm package.json, node_modules 03 How Node.js Works Event loop, blocking vs non-blocking 04 Modules and Imports Your first custom module 05 File System Module Read, write, update, delete files Sample code from Session 05 const fs = require ( " fs " ); // Create a file fs . writeFileSync ( " student.txt " , " Welcome To Node.js " ); // Read the file const data = fs . readFileSync ( " student.txt " , " utf8 " ); console . log ( data ); // Welcome To Node.js // Append to file fs . appendFileSync ( " student.txt " , " \n New line added " ); // Delete file fs . unlinkSync ( " student.txt " ); Phase 2 - Core Modules (Sessions 6-10) Session Topic What You Will Build 06 Path Module Cross-platform file paths 07 OS Module System information 08 Events and EventEmitter Custom event handling 09 HTTP Module Create a server 10 Multi-Route Server Multiple routes, JSON responses Sample code from Session 10 const http = require ( " http " ); const server = http . createServer (( req , res ) => { if ( req . url === " / " ) { res . end ( " Home Page " ); } else if ( req . url === " /about " ) { res . end ( " About Page " ); } else if ( req . url === " /products " ) { res . setHeader ( " Content-Type " , " application/json " ); res . end ( JSON . stringify ([{ id : 1 , name : " Laptop " }])); } else { res . statusCode = 404 ; res . end ( " Page Not Found " ); } }); server . listen ( 3000 ); Phase 3 - Building REST APIs (Sessions 11-15) Session Topic What You Will Build 11 CRUD with Dummy Data Complete REST API using array 12

2026-06-13 原文 →
AI 资讯

Beyond the Happy Path: Lessons in Resilience and Distributed State

Reflecting on two major technical challenges from my backend engineering internship, focusing on fault tolerance, infrastructure, and distributed architectures. Introduction As I wrap up my HNG internship, I’ve been reflecting on the gap between code that "works on my machine" and code that survives in production. Here is a look at two tasks from Stage 9—one solo, one team-based—that completely changed how I approach backend engineering and infrastructure. The Individual Task: Background Job Scheduler What it was For my individual Stage 9 task, I built a distributed background job scheduler backed by PostgreSQL and a FastAPI backend, featuring a vanilla HTML/CSS/JS frontend. It manages async tasks (like a mock email sending queue) using a MinHeap priority queue, Directed Acyclic Graph (DAG) dependency resolution, a Dead-Letter Queue (DLQ), and a real-time Server-Sent Events (SSE) dashboard. The problem it was solving Heavy asynchronous tasks—like email generation or batch processing—cannot block the main API thread. The system needed to successfully queue, prioritize, retry on failure, and track every job entirely independently from the standard request-response cycle. How I approached it I built the core logic from the ground up: a MinHeap and an alternative Timing Wheel algorithm for scheduling, a worker engine featuring a 3-attempt backoff sequence (1s, 5s, 25s with jitter), a DAG dependency checker, and a starvation daemon to prevent tasks from hanging. Once the CRUD API and SSE streaming were hooked up, I containerized the entire application with Docker and wrote my deploy scripts. I thought I was done. What actually broke and how I fixed it The application code took hours. The deployment took a full day of non-stop debugging across multiple cloud providers. Oracle Cloud was out of capacity on every free tier shape, and GCP demanded upfront payment. I finally got a t3.micro running on AWS, but that’s when the real DevOps nightmare began: The SSL Chicken-and-Egg

2026-06-13 原文 →
AI 资讯

Two HNG Tasks That Taught Me More Than the Spec: OAuth for Three Clients, and Shipping AI on a Team Deadline

Two HNG Tasks That Taught Me More Than the Spec This is my Stage 9B write-up for the HNG internship . No new code just two tasks that stuck: one I owned solo across multiple repos, and one I shipped inside a team product under real deadline pressure. If you've ever had auth work almost done for three days straight, or watched an LLM politely ignore your JSON schema, you'll recognize these stories. Task 1 (Individual): Insighta Labs — One API, Three Clients, One Auth System Stage: 3 (Technical Requirements Document / TRD track) Why I picked it: Auth looked "done" on paper. It wasn't. Web portal, CLI, and graders all needed to log in differently, and every environment (localhost, Railway, preview URLs) found a new way to break. What it was Insighta Labs is a queryable profile-intelligence API I built during HNG. By Stage 3 the backend wasn't just CRUD anymore it needed GitHub OAuth with PKCE , JWT access + refresh with rotation , RBAC ( admin vs analyst ), rate limits, API versioning, and three first-class clients : Client Repo How it authenticates Backend API HNG_STAGE-1 Issues tokens, sets cookies Web portal Insighta-WebPortal HTTP-only cookies + CSRF CLI Insighta-Cli PKCE + local callback + Bearer tokens Every /api/* route required X-API-Version: 1 and a valid session. Access tokens expired in 3 minutes ; refresh tokens in 5 minutes with rotation. That sounds harsh, it was intentional, and it surfaced bugs fast. The problem it was solving Reviewers and real users had to prove identity without sharing one login mechanism. Browsers should never see raw tokens in JavaScript. The CLI can't use cookie redirects the same way a React app does. Automated graders needed a test path that didn't depend on GitHub's OAuth exchange. One auth design. Three runtimes. Zero "works on my machine only." How I approached it I split auth into explicit paths instead of one generic "login" handler: Web flow GET /auth/github — server stores PKCE verifier, redirects to GitHub GET /auth/gith

2026-06-12 原文 →
AI 资讯

When code becomes cheaper, what still makes an engineer valuable?

When code becomes cheaper, what still makes an engineer valuable? Recently, while writing my cover letter for remote roles and Upwork projects, I asked myself a very direct question: Why should a remote team or client choose me, especially in the AI era? I do not think the answer should be: “Because I am the strongest engineer technically.” That is not how I want to position myself. What I want to become is this: A backend engineer who can turn unclear business problems into reliable, maintainable systems. AI is making implementation faster. It can generate code, explain technologies, and provide alternatives. At the same time, remote work and platforms like Upwork make competition more global. We are not only competing with engineers nearby, but also with engineers from everywhere. If the only question is “Who knows more frameworks, patterns, or tools?”, many ordinary engineers may feel hopeless. But I believe there is another path. In real systems, code is only part of the work. Someone still needs to understand the business workflow. Someone still needs to define what “correct” means. Someone still needs to identify risks, edge cases, performance concerns, and reliability boundaries. My usual way of working starts from these questions: What is the real requirement? What does correctness mean in this workflow? What data must stay consistent? What edge cases could break the process? What performance or reliability signals should be protected? Where should the module boundary be? Who should orchestrate the main flow, and who should act as collaborators? This “orchestrator + collaborators” thinking helps me keep the main business process clear. The orchestrator owns the workflow. The collaborators handle specific responsibilities such as validation, translation, persistence, messaging, or external integration. I also use AI in this process, but not only to generate code. I use it to challenge my assumptions, explore alternatives, find missing cases, improve naming, r

2026-06-12 原文 →
AI 资讯

I Built My Own API Gateway in Rust — Here's What I Learned

Every backend project I've worked on eventually hits the same wall. You start clean — one service, simple routes, everything works. Then slowly the requirements creep in. "We need rate limiting." "Can we add auth middleware?" "What happens when the user service goes down — does it take everything else with it?" You either bolt these things onto every service individually, copy-paste the same middleware across projects, or pay for a managed gateway like Kong or AWS API Gateway and hope it does what you need. I wanted to actually understand how these things work under the hood. So I'm building one — and this is what I've learned so far. What is Ferrox? Ferrox is a self-hosted, programmable API gateway written entirely in Rust. It sits in front of your backend services and handles everything a production system needs in one place: Dynamic routing — point any path prefix to any upstream service Authentication — JWT and API key validation on protected routes Rate limiting — Redis-backed per-IP and per-API-key limiting Circuit breaking — stops hammering a dead upstream service Response caching — Redis-backed TTL cache per route Real-time observability — WebSocket dashboard with live request stats Prometheus metrics — plug straight into Grafana The idea is simple. Instead of this: Client → Service A (has its own auth, rate limiting, logging) Client → Service B (has its own auth, rate limiting, logging) Client → Service C (has its own auth, rate limiting, logging) You get this: Client | v FERROX (auth, rate limiting, circuit breaking, logging — once) | +--------+--------+ | | | Svc A Svc B Svc C (clean) (clean) (clean) Your services stay clean. Ferrox handles the cross-cutting concerns. Why Rust? Honest answer — I already knew Rust from my backend work. But for a gateway specifically, it felt like the obvious choice. A gateway sits on the critical path of every single request. Every millisecond of latency it adds is latency your users feel. You need predictable performance

2026-06-10 原文 →
AI 资讯

Inngest + Next.js: The Complete Guide (2026)

Serverless functions have a time limit. Vercel gives you 60 seconds on Pro. None of that is enough to send a welcome email sequence, process an uploaded CSV, or run any workflow with multiple external API calls. Inngest solves this by turning your Next.js API routes into reliable, retryable, observable background jobs — without Redis, without a worker process, without any separate queue infrastructure. Read the full guide with all code examples at stacknotice.com How It Works You define functions that run in response to events . When an event fires, Inngest calls your function via HTTP. If the function fails, Inngest retries it. If the function has multiple steps, Inngest checkpoints each step so a failure halfway through doesn't restart from scratch. Setup npm install inngest // lib/inngest/client.ts import { Inngest } from ' inngest ' export const inngest = new Inngest ({ id : ' my-app ' }) // app/api/inngest/route.ts import { serve } from ' inngest/next ' import { inngest } from ' @/lib/inngest/client ' import { welcomeSequence } from ' @/lib/inngest/functions/welcome ' export const { GET , POST , PUT } = serve ({ client : inngest , functions : [ welcomeSequence ], }) Welcome Email Sequence export const welcomeSequence = inngest . createFunction ( { id : ' welcome-email-sequence ' , retries : 3 }, { event : ' user/signed-up ' }, async ({ event , step }) => { const { userId , email , name } = event . data // Each step is independently retried await step . run ( ' send-welcome-email ' , async () => { await resend . emails . send ({ from : ' hello@yourapp.com ' , to : email , subject : `Welcome, ${ name } !` , html : `<p>Thanks for signing up...</p>` , }) }) await step . sleep ( ' wait-2-days ' , ' 2 days ' ) await step . run ( ' send-tips-email ' , async () => { await resend . emails . send ({ from : ' hello@yourapp.com ' , to : email , subject : ' Top 5 tips to get the most out of the app ' , html : `<p>Here are the tips...</p>` , }) }) await step . sleep ( ' wait

2026-06-10 原文 →
AI 资讯

Why I Stopped Using reset() and end() in PHP (And What I Use Now)

If you have been writing PHP for a year or two, you have almost certainly written something like this: $items = getFilteredOrders (); $first = reset ( $items ); $last = end ( $items ); It works. It runs. It looks fine in code review. And it contains a subtle bug waiting to happen. The problem with reset() and end() Both functions move PHP's internal array pointer as a side effect. PHP arrays have a hidden cursor that tracks "the current position" in the array. Functions like current() , next() , prev() , and each() depend on where that cursor sits. reset() moves it to the first element. end() moves it to the last. This is harmless in an isolated script. But in a real application, the same array often passes through multiple functions — and any function that relies on the cursor position after your call will get unexpected results. Here is a concrete example: function getFirstActiveOrder ( array $orders ): ?array { // Moves the pointer to the first element $first = reset ( $orders ); foreach ( $orders as $order ) { if ( $order [ 'status' ] === 'active' ) { return $order ; } } return null ; } At first glance this looks fine. But foreach in PHP actually resets the pointer to the beginning before iterating — so in this simple case you get lucky. The bug shows up in less obvious situations: when you call reset() inside a function that the caller is already iterating with current() / next() , or when you use end() to peek at the last item while a foreach is in progress on the same array reference. The deeper issue: reset() and end() return false on an empty array. But false might also be a legitimate value stored in your array: $flags = [ true , false , true ]; $last = end ( $flags ); // returns false — but is this "empty array" or "the value false"? You have to write: if ( $flags === [] || end ( $flags ) === false ) { ... } Which is already awkward. And it still mutates the pointer. The modern solution: array_key_first() and array_key_last() PHP 7.3 introduced two functi

2026-06-10 原文 →
AI 资讯

What Happens When a Database Operation Fails Midway? NestJS Transactions to the Rescue

Imagine a simple money transfer scenario. John sends money to his friend Sarah. The system successfully deducts money from John's account, but before it can credit Sarah's account, the application crashes. Without proper safeguards, John's money would disappear from the system, creating inconsistent and unreliable financial records. To prevent this type of problem, database transactions are used. Transactions ensure that a group of related database operations either complete successfully together or fail together. If any part of the process encounters an error, all changes are reverted, ensuring that the database remains consistent. Transactions make database operations atomic. Atomicity means that all operations inside a transaction are treated as a single unit of work. Either every operation succeeds and is committed to the database, or all operations fail and are rolled back. Partial updates are never permanently stored. A database transaction is a group of one or more database operations executed as a single unit. Either all operations succeed together or all operations fail together. This guarantees database consistency even if an application crashes, a network failure occurs, or an unexpected error is encountered during execution. It is important to understand that a transaction is not simply a single database query. While individual queries such as save, update, or delete interact with the database, a transaction wraps multiple queries inside a controlled all-or-nothing boundary. This prevents partial updates and ensures data integrity throughout the process. Prerequisites Before starting, make sure you have the following: Basic knowledge of NestJS Basic understanding of TypeORM Basic knowledge of PostgreSQL Understanding of basic database operations (save, update, delete) in TypeORM Project Setup In this article, we will create a simple NestJS application to demonstrate the importance of transactional queries when multiple database write or update operations

2026-06-10 原文 →
AI 资讯

FastAPI for AI Engineers - Part 4: Stop Bad Data Before It Breaks Your API (Pydantic and Data Validation)

In the previous article, we connected our FastAPI application to a database using SQLite and SQLAlchemy. We also used classes like: class StudentCreate ( BaseModel ): name : str department : str cgpa : float without fully understanding what was happening behind the scenes. Today, we'll fix that. If you haven't read it check it out: FastAPI for AI Engineers - Part 3: Connecting to a database Ananya S Ananya S Ananya S Follow Jun 6 FastAPI for AI Engineers - Part 3: Connecting to a database # ai # fastapi # python # backend 6 reactions Add Comment 6 min read Why Do We Need Data Validation? Imagine you're building a weather application. A user asks: What is the temperature in Chennai? A valid response might be: 35 or 35°C But what if the API returns: Sunny This is clearly wrong. Temperature should be represented as a number. Even if the value itself is inaccurate, we still know that temperature must be numeric. This is where validation becomes important. Validation allows us to define rules about what data is acceptable before it enters our application. For example: Temperature should be numeric Age cannot be negative CGPA should be between 0 and 10 Email addresses should follow a valid format Without validation, applications can receive invalid data and behave unexpectedly. The Problem Without Validation Consider a student registration API. @app.post ( " /student " ) def create_student ( student ): return student A user could send: { "name" : "Ananya" , "cgpa" : "Excellent" } The API would accept it. But a CGPA should be a number, not text. As applications grow, manually checking every field becomes difficult. We need a better solution. Enter Pydantic Pydantic is a Python library used for data validation. FastAPI uses Pydantic extensively behind the scenes. Instead of manually validating data, we define a schema. from pydantic import BaseModel class Student ( BaseModel ): name : str cgpa : float Now FastAPI knows: name must be a string cgpa must be a floating-point nu

2026-06-09 原文 →
AI 资讯

32/60 Days System Design Questions!

Your startup just got its first SOC 2 audit. The auditor asks: "Where are your database passwords, API keys, and service tokens stored?" Your senior engineer goes quiet. Turns out half of them are in .env files committed to git 18 months ago. Three are hardcoded in Lambda environment variables. One is in a Slack message from 2023. You have 6 services in production, 4 environments, and zero rotation policy. Here's the setup: • NestJS API → Postgres (password in env var) • NestJS API → Stripe (API key in env var) • Background workers → SQS, S3 (AWS credentials in env var) • 3rd-party webhooks → HMAC secrets in env var • Zero rotation. Zero audit trail. Zero centralized access control. You need to fix this. And you can't take downtime. A) Move everything to AWS Secrets Manager — SDK calls at runtime, IAM controls access, auto-rotation built in. B) Use HashiCorp Vault — dynamic secrets, fine-grained policies, works across any cloud or on-prem. C) Use environment variables injected at deploy time via CI/CD — secrets stored in GitHub Actions / GitLab CI secrets vault, never touch disk. D) Encrypt secrets with KMS and store ciphertext in your own database — decrypt at runtime, full control. All four are used in production at real companies. Pick one — A, B, C, or D — and tell me why. I'll drop the full breakdown in the comments. If your team is having this argument right now, share this post. Someone needs to see it. Drop your answer 👇 30DaysOfSystemDesign #SystemDesign #BackendEngineering #CloudArchitecture

2026-06-08 原文 →
AI 资讯

Architecting Strict Sequential Ordering in a Concurrent World

Imagine you are building a cloud-native backend for a high-frequency trading platform or a core banking ledger. To ensure mathematical immutability and prevent silent data tampering, compliance mandates that every transaction for a specific financial account must be cryptographically chained. This means the signature of Transaction #50 must explicitly include the cryptographic hash of Transaction #49. You cannot sign them out of order, and the backend is strictly responsible for generating and validating this chain. This introduces a massive distributed systems headache: How do you enforce strict, sequential ordering while maintaining the concurrency required to scale a modern cloud architecture? Let's walk through the evolution of this system, deconstruct exactly how the standard event-driven approach fails in production, and examine the Staff-level architecture required to fix it. Phase 1: The MVP & The Database Bottleneck In the early days, traffic is low. An account might see one transaction every few minutes. The "Happy Path" is simple: The API receives a deposit request for Account A. The API queries Postgres for the last_signature_hash . The API computes the new hash in memory: SHA(last_hash + new_transaction_data) . The API writes the new transaction and updates the state. The Pitfall: The Thundering Herd To prevent two concurrent requests from reading the same previous hash, you wrap the database operation in a pessimistic lock: SELECT ... FOR UPDATE . This forces the database to serialize requests at the row level. When a massive partner bank initiates a bulk sync, dumping 5,000 transactions for a single corporate account onto the API in two seconds, 4,999 concurrent threads immediately hit the FOR UPDATE lock and block. The database connection pool is instantly exhausted, latency spikes platform-wide, and the MVP dies. The Insight: The database must be your last line of defense, not your primary queueing mechanism. Contention must be solved upstream in me

2026-06-07 原文 →
AI 资讯

A practical SQL query tuning playbook: execution plans, joins, indexes, and the traps

SQL tuning is the process of making a database query run faster and cheaper — cutting response time while minimizing the system resources it burns. Here's the playbook I actually use, from "this query is slow" to "this query is fixed," with the traps that bite people in the middle. The loop Tuning is iterative. The shape is always the same: Identify the problem. Find the slow query (logs, profiler, or user feedback) and measure a baseline — execution time and resource usage. You can't claim an improvement you didn't measure. Analyze & rewrite. Review the SQL for redundant joins, unnecessary work, and complex subqueries. Tighten the WHERE , select only the columns you need, convert subqueries to joins where it helps. Read the execution plan. Understand how the engine actually runs the query; find inefficient join orders and needless full scans. Revisit indexes. Evaluate whether existing indexes help; add or restructure as needed. Consider schema changes. If a column is updated so often that indexing it hurts, split it out. Sometimes the model is the bottleneck. Tune settings/hardware if it comes to that. Re-test and repeat. Apply changes, re-check the plan, confirm the gain, monitor. Reading an execution plan The execution plan shows how the DB will run your query — table scans, index access, join methods. Read it well and you can pinpoint where the time goes. Most engines expose it: EXPLAIN (MySQL/PostgreSQL), EXPLAIN PLAN FOR (Oracle), SET SHOWPLAN_ALL ON (SQL Server). Operators to know: Full Table Scan — reads every row. Happens when there's no suitable index, or the query can't use one. Index Scan — scans via an index; usually cheaper than a table scan. Index Seek — jumps to specific key values; very efficient, reads only the rows it needs. Nested Loops / Hash Join / Merge Join — the three ways to join two tables (more below). Sort — orders data; excessive sorting is a common performance drag. Three numbers that matter: Cost — estimated resources a step will cons

2026-06-07 原文 →
AI 资讯

Online School, Messy Billing, and the Proration Rabbit Hole

While designing the database and Product Requirements Document (PRD) for an online school project, I ran into a problem I was not expecting. The school had multiple subscription plans. For simplicity, imagine: Live Class Plan:₦50,000 per term Video On Demand Plan: ₦30,000 per term Hybrid Plan (Live Classes + Video On Demand):₦70,000 per term. Initially this looked simple. Students subscribe. System charges them. Done. Then I asked: What happens if somebody changes plans halfway through the term? Suppose: A student already paid: Live Class Plan ₦50,000 Two months later: They decide: Upgrade to Hybrid Plan Do we charge: ₦70,000 again? That would be unfair. Do we charge: ₦20,000 difference? Maybe. But what if they already used most of their subscription period? This question led me to something called: Proration What Is Proration? Proration simply means: Charging customers only for the portion they actually use. Instead of pretending subscriptions always begin and end perfectly. Proration tries to answer: "How much value remains in the current subscription?" and "How much should the customer pay for the new one?" Simple Example Assume: Term Length: 100 Days Student buys: Live Plan ₦50,000 After: 40 Days they upgrade. This means: Used: 40 Days Remaining: 60 Days Value remaining: Remaining Value = Remaining Days / Total Days = 60 / 100 = 60% Remaining credit: 60% × ₦50,000 = ₦30,000 Hybrid costs: ₦70,000 Therefore: Amount to bill = New Plan Price − Remaining Credit = ₦70,000 − ₦30,000 = ₦40,000 Student pays: ₦40,000 instead of: ₦70,000 This feels fairer. Downgrades Are More Complicated What if: Hybrid user: ₦70,000 moves to: ₦30,000 plan Should the system: Refund money? Create account credits? Apply discount later? Ignore downgrades until renewal? This is where: Proration Rules become important. What Are Proration Rules? Proration calculations are useless without rules. The business must decide: Rule 1: How Is Remaining Value Calculated? Options: Daily basis Weekly basis

2026-06-06 原文 →
AI 资讯

FastAPI for AI Engineers - Part 3: Connecting to a database

In the previous article, we explored how to build our first CRUD API using FastAPI. While our API worked correctly, there was one major problem. We were storing data inside Python lists, which exist only in memory. If you've ever wondered how applications like Instagram, LinkedIn, or ChatGPT remember information even after a server restart, the answer is simple: databases. In this article, we'll solve the problem of in-memory storage by connecting our FastAPI application to SQLite using SQLAlchemy. If you haven't read the previous post, check it out: FastAPI for AI Engineers - Part 2: Building Your First CRUD API Ananya S Ananya S Ananya S Follow Jun 1 FastAPI for AI Engineers - Part 2: Building Your First CRUD API # ai # backend # fastapi # python 7 reactions Comments Add Comment 4 min read By the end of this article, you'll understand: Why in-memory storage is a problem What SQLite is What SQLAlchemy is How ORM works How to create database tables using Python classes How to perform CRUD operations using a real database The Problem with In-Memory Storage Previously, our application stored students inside a Python list. students = [ { " id " : 1 , " name " : " Ananya " , " department " : " CSE " , " cgpa " : 8.9 } ] This worked for learning CRUD operations. However, consider what happens when the server restarts: FastAPI Server Stops ↓ Python Memory Cleared ↓ All Student Data Lost This is unacceptable in real-world applications. We need a place where data can survive application restarts. This is where databases come in. What is SQLite? SQLite is a lightweight relational database. Unlike MySQL or PostgreSQL, SQLite doesn't require a separate database server. Instead, everything is stored inside a single file. students.db Advantages of SQLite: No installation required Lightweight Easy to learn Perfect for local development Great for small projects For this article, we'll use SQLite. What is SQLAlchemy? Before SQLAlchemy, developers often wrote raw SQL queries. Exampl

2026-06-06 原文 →
AI 资讯

How I Built a Hotel AI Platform in Go (And Every Honest Technical Debt We're Carrying)

Building Stayzr meant solving real problems: PMS integration, high-throughput webhook handling, and AI that actually knows your property. Here's how we architected it. The Stack (What's Running in Production) Backend: Go 1.23 with Fiber framework, pgx/v5 connection pooling, Bun ORM over PostgreSQL, Redis for caching/sessions, OpenTelemetry for tracing AI Agents Service: Python 3.11 + FastAPI (Uvicorn), LangChain primitives, Qdrant for knowledge base, ChromaDB for conversation memory Frontend: Next.js 15 / React admin UI + marketing site 3rd-party Integrations: Mews (PMS), WhatsApp Business/Meta, Resend + Postmark (email), Azure Blob Storage (files), Gemini + OpenAI (LLM + embeddings), Infisical (secrets), SigNoz + Oneuptime (observability) It's a polyglot monorepo: Go where throughput and concurrency matter (API, dispatch, sync), Python where the LLM/RAG ecosystem lives. Why Go Over Python/Node/Java? For the parts handling concurrent I/O — PMS sync workers, email dispatch worker, webhook fan-in — Go's goroutines + channels let us run in-process worker pools without pulling in a broker or heavyweight async runtime. The dispatch worker is a for{ select } loop over a ticker and wake channel — simple and effective for our use case. We kept Python only for the agents service because that's where LangChain, Gemini/OpenAI SDKs, and vector-store clients live. The honest answer: Go for systems work, Python where AI tooling requires it. Multi-Tenancy: Row-Level Isolation Shared database, shared schema, row-level isolation by organizationId . Every tenant-scoped table carries an organizationId , with a TenantDB wrapper in the data layer that auto-appends organization_id = $N to queries. Middleware ( MultiTenantContext / RequireTenant ) resolves the org from the X-Organization-ID header, query param, cookie, or JWT claim. Below org we scope further by propertyId (a hotel can have multiple properties). The AI memory store enforces the same boundary differently — every guest's co

2026-06-04 原文 →
AI 资讯

Stop Hardcoding 301s: How I Built a Redirect Engine That Doesn't Break at 2 A.M.

Marketing wants an A/B landing page by Friday. Product wants to gracefully deprecate a legacy API without breaking old mobile clients. Growth wants ten thousand short links, and Ops does not want ten thousand Nginx edits. At some point, a single return 301 in your CDN stops being a configuration problem and becomes a routing product . Someone has to answer, on every HTTP request: Given this host, path, query, and method—where does this visitor go, and with which status code? I built that answer as a pipeline at LinkShift . Not a pile of special cases, but a fixed sequence of steps that runs the exact same way for real visitors and for the tools you use to test rules before rollout. Here is how I designed a deterministic redirect engine, the pipeline that powers it, and the edge cases that kept me up at night so they don't have to keep you up. Why "Usually Works" Is Not Enough A redirect engine fails quietly. The browser follows a broken 302 and nobody files a ticket. The damage shows up days later in analytics: wrong campaign, wrong locale, or an infinite loop that only appears when two rules on the same host point at each other. What I wanted early on was boring, bulletproof reliability: Same inputs → same decision. Two engineers simulating the same request against the same rule set should get the same target URL. Same resolution logic everywhere. Matching and destination resolution must not diverge between the "Test Rule" button in the dashboard and an actual click on a custom domain. Guards before cleverness. Rate limits and access checks run before anyone evaluates a ternary conditional in a destination string. Expressiveness is easy. Ordering is what saves you in production. The Pipeline, Told as a Story Picture a request hitting a hostname. Before the engine asks "which rule wins?", the request walks through a strict corridor of gates. Only then does it enter the rule loop. Gate 1: The Host Has to Exist If the hostname does not resolve to a domain or LinkShift

2026-06-04 原文 →
AI 资讯

TryParse Looks Like a Small Utility Method — Until You Realize It Prevents Entire Classes of Production Failures

Why Senior .NET Engineers Rarely Trust User Input Most beginner C## developers discover TryParse() while learning console applications. It usually appears during a simple exercise: Console . Write ( "Enter quantity: " ); string ? input = Console . ReadLine (); if ( int . TryParse ( input , out int quantity )) { Console . WriteLine ( $"Quantity: { quantity } " ); } At first glance, it looks like a convenience method. A safer version of Parse() . A small utility. Nothing particularly interesting. But experienced .NET engineers see something completely different. They see one of the earliest examples of defensive programming. Because software engineering is not about handling perfect input. It is about surviving imperfect input. And in production systems, imperfect input is the rule—not the exception. TL;DR TryParse() is not just a conversion method. It introduces some of the most important concepts in professional software development: Defensive programming Input validation Runtime safety Exception avoidance Financial precision Domain modeling Reliability engineering Understanding why TryParse() exists is often more valuable than learning how to use it. Every Value in C## Starts With a Type One of the first concepts developers learn is that every variable has a type. int quantity = 10 ; decimal price = 25.99M ; string productName = "Laptop" ; bool isAvailable = true ; Simple. Yet this idea is foundational. Because types are not just containers. They are contracts. Each type defines: Valid values Memory layout Available operations Precision guarantees Runtime behavior When you choose a type, you are making an architectural decision. Why decimal Exists Many developers ask: Why not use double for money? Because financial systems require precision. Consider: double a = 0.1 ; double b = 0.2 ; Console . WriteLine ( a + b ); Expected: 0.3 Reality: 0.30000000000000004 The issue comes from binary floating-point representation. For scientific calculations, this is acceptable. F

2026-06-04 原文 →
AI 资讯

Building a API in PHP

Books API Structure Create folders app/ app/controllers/ app/core/ app/models/ app/models/DAOs/ app/models/DTOs/ app/models/entities/ app/utils/ config/ public/ api/composer.json Configure Composer and the PSR-4 autoload so that classes with the namespace App\ are searched inside the app/ folder. Key content: { "name": "user/api", "autoload": { "psr-4": { "App\": "app/" } } } After creating it, run this command inside the api folder: composer dump-autoload api/config/config.php Defines the base URL of the project. The router removes it from REQUEST_URI to keep only routes such as /books/get. <?php define('BASE_URL', '/proyect/api/public'); api/config/dbconf.json MySQL DB connection: { "host": "localhost", "user": "root", "password": "", "db_name": "books_db" } api/public/.htaccess Makes Apache send all routes to index.php. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [QSA,L] api/public/index.php This is the entry point. It loads Composer, loads the configuration and calls the router. <?php use App\Core\Router; require_once DIR . '/../vendor/autoload.php'; require_once DIR . '/../config/config.php'; (new Router())->dispatch($_SERVER['REQUEST_URI']); api/app/core/Router.php <?php namespace App\Core; class Router { protected array $routes = [ '/' => 'HomeController@index', '/books' => 'BookController@index', '/books/get' => 'BookController@getAll', '/books/getById' => 'BookController@getById', '/books/create' => 'BookController@create', '/books/update' => 'BookController@update', '/books/delete' => 'BookController@delete', ]; public function add($route, $params): void { $this->routes[$route] = $params; } public function dispatch($uri): void { $uri = parse_url(str_replace(BASE_URL, '', $uri), PHP_URL_PATH); if (!isset($this->routes[$uri])) { $this->sendNotFound(); return; } [$controller, $method] = explode('@', $this->routes[$uri]); $controller = 'App\\Controllers\\' . $controller; if (!class_exists($co

2026-06-04 原文 →
AI 资讯

Stop Juggling 5 Tools , Python's uv Does It All (And It's Blazing Fast)

If you've been writing Python for more than a year, you know the ritual. A new project. A fresh terminal. And then: pyenv install 3.12.3 pyenv local 3.12.3 python -m venv .venv source .venv/bin/activate pip install pip --upgrade pip install -r requirements.txt Six commands before you've written a single line of code. And that's if nothing breaks. Enter uv a single binary that replaces pip , virtualenv , pip-tools , pyenv , and pipx . Written in Rust. 10–100x faster than pip. And honestly, one of the most pleasant tools I've used in the Python ecosystem in years. Let's dig into it. What Even Is uv ? uv is a Python package and project manager built by Astral , the same team behind ruff , the linter that everyone switched to and never looked back. The goal is simple: be the Cargo for Python . One tool, one lockfile, no friction. It's a standalone binary with zero Python dependencies, which means it works even before Python is installed. Installing uv # macOS / Linux curl -LsSf https://astral.sh/uv/install.sh | sh # Windows (PowerShell) powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" # Or via pip if you prefer pip install uv Verify: uv --version # uv 0.9.x The Speed Claim Is It Real? Yes. Embarrassingly so. Here's a timed comparison on Apple Silicon (Python 3.14): Operation pip / venv uv Create virtual env ~2 seconds 35 milliseconds Install FastAPI + deps (cold) ~12s ~1.2s Install with warm cache ~8s ~0.1s The warm cache case is where uv really shines it uses a global cache and hard-links packages into environments instead of copying them. If you've installed requests in any previous project, your next project gets it nearly instantly. Starting a New Project This is where uv feels like a completely different world: uv init my-api cd my-api That single command gives you: my-api/ ├── .git/ ├── .venv/ ← already created ├── .python-version ├── pyproject.toml ├── README.md └── main.py No separate python -m venv , no git init , no template c

2026-06-03 原文 →