惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
月光博客
月光博客
雷峰网
雷峰网
WordPress大学
WordPress大学
博客园 - 司徒正美
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Help Net Security
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security @ Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
爱范儿
爱范儿
W
WeLiveSecurity
J
Java Code Geeks
Forbes - Security
Forbes - Security
H
Hacker News: Front Page
T
Threatpost
The Cloudflare Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
Netflix TechBlog - Medium
Latest news
Latest news
V2EX - 技术
V2EX - 技术
小众软件
小众软件
T
The Blog of Author Tim Ferriss
A
Arctic Wolf
B
Blog RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
C
Check Point Blog
N
News | PayPal Newsroom
Cyberwarzone
Cyberwarzone
V
V2EX
TaoSecurity Blog
TaoSecurity Blog
P
Privacy & Cybersecurity Law Blog
Microsoft Security Blog
Microsoft Security Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
D
DataBreaches.Net
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
K
Kaspersky official blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google DeepMind News
Google DeepMind News
C
CXSECURITY Database RSS Feed - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Strangler Fig in Go: Migrating a Monolith Without a Big-Bang Rewrite
Gabriel Anha · 2026-04-30 · via DEV Community

You inherit a Go monolith. One repo, forty handlers, one Postgres database, two integrations stitched into the HTTP layer. Someone proposes the rewrite. Three months of design docs, a freeze on new features, a parallel repo nobody uses in production. Six months in, the rewrite is shipped to staging and abandoned because the business needed a checkout fix and there was no team left to do it.

Martin Fowler called the alternative the Strangler Fig. The metaphor comes from a real plant: a fig seed sprouts in the canopy of a host tree, drops roots down the trunk, and over years grows into a hollow lattice. By the time the host tree dies, the fig is structurally complete. There is no day when the tree falls.

You can run the same pattern on a Go monolith. Route by route, integration by integration, the legacy code gets enveloped, redirected, and eventually deleted. Each step is a single PR behind a feature flag. The monolith keeps serving traffic the entire time.

The single-service hex migration reshaped one Go service in place. The strangler fig grows several small hex services out of a monolith. Different problem, different shape.

The seven-step pattern

The seven steps in order:

  1. Identify the seams — HTTP routes, DB tables, external integrations.
  2. Extract shared types into a domain module.
  3. Define ports (interfaces) for each seam.
  4. Wrap the legacy implementation in an adapter (the anti-corruption layer).
  5. Reroute traffic via a thin proxy in front of the monolith.
  6. Run a shadow read against the new service to prove parity.
  7. Cut over with the flag, delete the legacy code path.

Each step is independently shippable. Each step is reversible by flipping a flag. The order matters. Skip the proxy step and you cannot do shadow reads. Skip shadow reads and cutover is a guess.

Step 1: Identify the seams

A seam is a place where the monolith already has a boundary you can lean on. Three kinds matter:

  • HTTP routes. Every URL pattern is a candidate. /checkout, /orders/{id}, /customers. Find them by reading the router.
  • Database tables. Tables that only one bounded context reads or writes. payments, coupons, inventory_holds.
  • External integrations. Anywhere the monolith calls Stripe, S3, an internal vendor adapter. These are already wrapped behind a function call. That function is a seam.

Pick the seam with the highest pain-to-risk ratio. /checkout is usually a good first target: changes there get the most scrutiny, the table set is small, and a regression is recoverable in seconds via the flag.

Make the inventory explicit. A migration.md at the repo root listing every route, every table it touches, and every integration. This is the map you will tick off over the next few months.

Step 2: Extract shared types into a domain module

Create internal/domain (or a separate Go module, domain/, if the new services will live in their own repos). Move the structs your business logic talks about — Order, Item, Coupon, Customer — into it. No json tags. No db tags. No ORM annotations.

// internal/domain/order.go
package domain

import "time"

type OrderStatus string

const (
    OrderPending   OrderStatus = "pending"
    OrderConfirmed OrderStatus = "confirmed"
    OrderCancelled OrderStatus = "cancelled"
)

type Order struct {
    ID         string
    CustomerID string
    Items      []Item
    TotalCents int64
    Status     OrderStatus
    CreatedAt  time.Time
}

type Item struct {
    ProductID  string
    Quantity   int
    PriceCents int64
}

Enter fullscreen mode Exit fullscreen mode

The monolith still uses its old SQL-tagged structs in handlers. That is fine. The domain types are the shared vocabulary the new services will speak. Existing handlers map to and from them at the boundary.

The check that the domain stays clean:

go list -f '{{.Imports}}' ./internal/domain/...
# should be: [time fmt errors context]
# should NOT contain: database/sql net/http encoding/json

Enter fullscreen mode Exit fullscreen mode

Wire that go list check into CI. Catch the leak at PR review and it is a one-line fix. Six months in, it is a week.

Step 3: Define a port per seam

For the /checkout seam, the port is one interface in the domain package:

// internal/domain/checkout.go
package domain

import "context"

type CheckoutRequest struct {
    CustomerID string
    Items      []Item
    CouponCode string
}

type Checkout interface {
    Create(
        ctx context.Context,
        req CheckoutRequest,
    ) (Order, error)
}

Enter fullscreen mode Exit fullscreen mode

The domain now has a contract for what "creating a checkout" means, independent of HTTP, gRPC, or background workers. You can write a fake Checkout for tests in five lines.

Define one port per seam, not one per handler. /orders and /orders/{id} both belong to the same Orders port. Keep ports narrow. Aim for two to four methods. Ten methods is usually a sign you have not found the actual bounded context yet.

Step 4: Wrap the legacy code as an adapter

This is the step that does almost nothing visible. The old monolith handler stays. You wrap it.

// internal/legacy/checkout_adapter.go
package legacy

import (
    "context"

    "yourapp/internal/domain"
    "yourapp/internal/monolith/handlers"
)

type CheckoutAdapter struct {
    mono *handlers.OrderHandler
}

func NewCheckoutAdapter(
    mono *handlers.OrderHandler,
) *CheckoutAdapter {
    return &CheckoutAdapter{mono: mono}
}

func (a *CheckoutAdapter) Create(
    ctx context.Context,
    req domain.CheckoutRequest,
) (domain.Order, error) {
    legacyOrder, err := a.mono.CreateOrderInternal(
        ctx,
        req.CustomerID,
        toLegacyItems(req.Items),
        req.CouponCode,
    )
    if err != nil {
        return domain.Order{}, translate(err)
    }
    return toDomainOrder(legacyOrder), nil
}

Enter fullscreen mode Exit fullscreen mode

The toLegacyItems, toDomainOrder, and translate helpers are pure mapping functions. They live in the same legacy package. Their job is to keep monolith types (handlers.OrderHandler, handlers.LegacyError, and the legacy SQL structs) from leaking out.

This is the anti-corruption layer. The "vendor" in this case is your own monolith. You translate its taxonomy into your domain's taxonomy at one boundary, so the rest of the system never has to care.

Ship this PR. Run the existing test suite. Nothing changes in production yet.

Step 5: Route traffic through a thin proxy

You need a layer that sits in front of the monolith and decides, per request, whether to forward to the monolith handler or to the new service. A reverse proxy in Go is short.

// proxy/checkout.go
package proxy

import (
    "net/http"
    "net/http/httputil"
    "net/url"
)

type Router struct {
    monolith     *httputil.ReverseProxy
    newService   *httputil.ReverseProxy
    useNewSvc    func(*http.Request) bool
}

func New(
    monoURL, newURL string,
    useNewSvc func(*http.Request) bool,
) (*Router, error) {
    mono, err := url.Parse(monoURL)
    if err != nil {
        return nil, err
    }
    svc, err := url.Parse(newURL)
    if err != nil {
        return nil, err
    }
    return &Router{
        monolith:   httputil.NewSingleHostReverseProxy(mono),
        newService: httputil.NewSingleHostReverseProxy(svc),
        useNewSvc:  useNewSvc,
    }, nil
}

Enter fullscreen mode Exit fullscreen mode

The ServeHTTP method picks per request based on the flag function:

func (r *Router) ServeHTTP(
    w http.ResponseWriter,
    req *http.Request,
) {
    if r.useNewSvc(req) {
        r.newService.ServeHTTP(w, req)
        return
    }
    r.monolith.ServeHTTP(w, req)
}

Enter fullscreen mode Exit fullscreen mode

The useNewSvc closure is your feature-flag boundary. Start with func(*http.Request) bool { return false }. All traffic still hits the monolith. The new service exists, listens, but receives nothing. You can deploy it for weeks before sending it a single real request.

When you flip the flag to a 1% rollout, that 1% experiences the new code path. Everyone else is on the monolith. A bad release means flipping back to false and reading logs at human speed.

Step 6: Shadow-read parity check

Before you actually serve user traffic from the new service, prove it produces the same answers as the monolith. The proxy fans out: respond from the monolith, but also call the new service in the background and compare.

// proxy/shadow.go
package proxy

import (
    "bytes"
    "io"
    "log/slog"
    "net/http"
    "net/http/httptest"
)

type Shadow struct {
    primary http.Handler
    shadow  http.Handler
    log     *slog.Logger
}

func NewShadow(
    primary, shadow http.Handler,
    log *slog.Logger,
) *Shadow {
    return &Shadow{primary, shadow, log}
}

Enter fullscreen mode Exit fullscreen mode

ServeHTTP clones the request body, replays the call against the shadow service, and diffs the response without ever blocking the real user on the shadow call. The pattern is: respond fast, shadow async, never let the shadow block the user.

func (s *Shadow) ServeHTTP(
    w http.ResponseWriter,
    req *http.Request,
) {
    body, _ := io.ReadAll(req.Body)
    req.Body = io.NopCloser(bytes.NewReader(body))

    primaryRec := httptest.NewRecorder()
    s.primary.ServeHTTP(primaryRec, req)
    copyResponse(w, primaryRec)

    go func() {
        shadowReq := req.Clone(req.Context())
        shadowReq.Body = io.NopCloser(
            bytes.NewReader(body),
        )
        shadowRec := httptest.NewRecorder()
        s.shadow.ServeHTTP(shadowRec, shadowReq)
        s.diff(primaryRec, shadowRec, req.URL.Path)
    }()
}

Enter fullscreen mode Exit fullscreen mode

The diff helper logs the path, status code mismatches, and body diffs. Point your alerting at it.

Shadow reads only. You do not shadow-write. Two writes against the same database against the same idempotency key will corrupt state. Read endpoints (GET /orders/{id}) are safe to shadow forever. Write endpoints get cut over directly with the flag and rolled back fast if metrics move.

Tolerate non-determinism. Timestamps, database autogenerated IDs, ordering of slices that should be sets. Build a normaliser into diff before you compare. If you cannot normalise, that is a hint the new service has a different contract. Fix the service, not the diff.

Teams that run this pattern often spend two to three weeks in shadow mode before cutover. The bugs that surface tend to be small and load-bearing: timezone-parsing differences, rounding mismatches on edge-case totals, the kind of thing that causes customer-visible errors when you cut over blind.

Step 7: Cut over and delete the legacy path

When the diff has been zero for long enough, flip useNewSvc from a percentage to true for the route. Watch the dashboards for an hour. Watch them for a day. Then come back to the codebase and delete:

  • The legacy handler in monolith/handlers/order.go.
  • The legacy adapter in internal/legacy/checkout_adapter.go — its job was to keep the monolith reachable during migration. Once nothing routes there, it is dead code.
  • The route entry in the monolith's router.
  • The flag, once it has been true in prod for a release cycle.

go vet ./... and staticcheck will help: anything unimported and unreferenced is a candidate. Do the deletion in its own PR. Reverting "delete dead code" is cheap; reverting "delete dead code AND ship a feature" mid-incident is not.

What you have at the end

After six or seven seams, the monolith has been hollowed out. The router's job is mostly forwarding to small hex services. Each new service has its own domain types, its own ports, its own adapters, and its own deploy. The remaining monolith is small enough that the next migration is the easy one, or you decide to leave it because it is fine.

Pick the seam with the highest pain-to-risk ratio on Monday. Ship the adapter Friday.


If this was useful

The strangler fig pattern, the anti-corruption layer, the port-per-seam approach — they all come from the same playbook. Hexagonal Architecture in Go walks the playbook end to end with tested code: how to define ports that survive vendor swaps, how to write adapters that translate without leaking, and how to migrate a real codebase without breaking the deploy pipeline.

The Complete Guide to Go Programming is the companion — the language fundamentals the architecture book assumes you have.

Thinking in Go — the 2-book series on Go programming and hexagonal architecture