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

推荐订阅源

K
Kaspersky official blog
Engineering at Meta
Engineering at Meta
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
B
Blog RSS Feed
GbyAI
GbyAI
P
Proofpoint News Feed
aimingoo的专栏
aimingoo的专栏
MyScale Blog
MyScale Blog
D
Docker
阮一峰的网络日志
阮一峰的网络日志
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recorded Future
Recorded Future
美团技术团队
The Register - Security
The Register - Security
V
Visual Studio Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Tailwind CSS Blog
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Blog of Author Tim Ferriss
博客园 - 司徒正美
量子位
B
Blog
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
雷峰网
雷峰网
大猫的无限游戏
大猫的无限游戏
J
Java Code Geeks
L
LangChain Blog
Latest news
Latest news
S
SegmentFault 最新的问题
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
W
WeLiveSecurity
T
Tenable Blog
T
Tor Project blog

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
DDD in Go applied to crypto exchange APIs
Odilon HUGON · 2026-04-26 · via DEV Community

You write CQRS. You talk about aggregates. You emit domain events. But where do these concepts come from? Domain-Driven Design. Without understanding DDD, CQRS is just a pattern you copy-paste and hope it holds. With DDD, it becomes a tool you use consciously, for the right reasons.

This article lays the conceptual foundations. The concrete terrain: a Go service consuming APIs from multiple crypto exchanges (Binance, OKEx, Coinbase). Because an Order in trading is something any trader understands — that's exactly the kind of domain where DDD pays off.

Domain first, technology second

DDD's core principle is uncomfortable when you come from a technical background: the business model takes precedence over technology. You don't start with "what database", or "what API does Binance expose". You start with "what is an Order in this system? What is a Position? What happens when an order is partially filled?"

For a crypto trading service, the domain is: orders you place, positions that evolve, market data arriving continuously, a portfolio whose value you monitor. Not "a Binance wrapper". Not "a websocket consumer". Those are implementation details.

The practical difference: if your model is domain-centric, you can replace Binance with OKEx without touching your business logic. If your model is API-centric, you rewrite everything every time an exchange changes an endpoint.

DDD doesn't say "ignore technology". It says "don't let technology contaminate your business model".

Bounded contexts: splitting without cutting to the bone

This is the most practical DDD concept, and the most frequently misunderstood. A bounded context is an explicit boundary inside which a model has a precise, coherent meaning. Outside that boundary, the same word can mean something different — and that's acceptable.

For a crypto trading service, three natural bounded contexts emerge:

Market Data

Prices, order books, tickers, recent trades. This context is read-heavy, near real-time. Binance can push 10 updates per second on BTC/USDT. The model here is simple: immutable snapshots. A Ticker in Market Data has no mutable state — it's just a value at a point in time.

Trading

Orders, executions, positions. This context is command-heavy. An Order here has a full lifecycle: created, submitted, partially filled, cancelled. Business logic is concentrated here: validation rules, exchange rejection handling, fee calculation. This is where your aggregates live.

Portfolio

Balances, P&L, trade history. This context is a read model oriented toward reporting. It consumes events emitted by Trading to maintain a coherent view of the portfolio. Updates can be slightly delayed — a few seconds of lag is acceptable for reporting.

Why separate them? Because they have radically different constraints. Market Data at 10 updates/sec doesn't need the same model as Portfolio reporting aggregating data over 3 months. Putting everything in the same model means making compromises that make everything more complex without any benefit.

Bounded Context

Load

Consistency

Business complexity

Market Data

Very high (websockets)

Eventual OK

Low

Trading

Moderate (commands)

Strong (transactional)

High

Portfolio

Low (read model)

Eventual OK

Low

Aggregates and Value Objects in Go

Two core DDD building blocks that Go implements naturally, without any framework.

A Value Object is immutable. Its identity is defined by its value, not by a reference. Price{Amount: 42000, Currency: "USD"} equals another Price with the same fields. In Go, this translates to a struct without a pointer, passed by value.


// Value Object — immutable, equality by value
type Price struct {
    Amount   decimal.Decimal
    Currency string
}

func (p Price) IsZero() bool {
    return p.Amount.IsZero()
}

func (p Price) Add(other Price) (Price, error) {
    if p.Currency != other.Currency {
        return Price{}, fmt.Errorf("currency mismatch: %s vs %s", p.Currency, other.Currency)
    }
    return Price{Amount: p.Amount.Add(other.Amount), Currency: p.Currency}, nil
}

type TradingPair struct {
    Base  string // "BTC"
    Quote string // "USDT"
}

func (tp TradingPair) String() string {
    return tp.Base + "/" + tp.Quote
}

Enter fullscreen mode Exit fullscreen mode

An Aggregate is a unit of consistency. All modifications go through its methods — never through direct field access. It guarantees that its business invariants are always upheld. And in event sourcing, it emits events to describe what happened.


type OrderStatus int

const (
    StatusPending   OrderStatus = iota
    StatusPartial
    StatusFilled
    StatusCancelled
)

// Aggregate — consistency guaranteed, modification through methods only
type Order struct {
    id           OrderID
    pair         TradingPair
    side         Side // Buy / Sell
    quantity     decimal.Decimal
    filledQty    decimal.Decimal
    status       OrderStatus
    events       []DomainEvent
}

func NewOrder(pair TradingPair, side Side, qty decimal.Decimal) (*Order, error) {
    if qty.IsZero() || qty.IsNegative() {
        return nil, fmt.Errorf("invalid quantity: %s", qty)
    }
    o := &Order{
        id:       NewOrderID(),
        pair:     pair,
        side:     side,
        quantity: qty,
        status:   StatusPending,
    }
    o.events = append(o.events, OrderCreated{
        OrderID: o.id,
        Pair:    pair,
        Side:    side,
        Qty:     qty,
    })
    return o, nil
}

func (o *Order) Fill(qty decimal.Decimal, price Price) error {
    if o.status != StatusPending && o.status != StatusPartial {
        return ErrOrderNotFillable
    }
    if qty.GreaterThan(o.quantity.Sub(o.filledQty)) {
        return fmt.Errorf("fill qty %s exceeds remaining %s", qty, o.quantity.Sub(o.filledQty))
    }

    o.filledQty = o.filledQty.Add(qty)
    if o.filledQty.Equal(o.quantity) {
        o.status = StatusFilled
    } else {
        o.status = StatusPartial
    }

    o.events = append(o.events, OrderFilled{
        OrderID: o.id,
        Qty:     qty,
        Price:   price,
    })
    return nil
}

func (o *Order) Cancel() error {
    if o.status == StatusFilled || o.status == StatusCancelled {
        return ErrOrderAlreadyTerminal
    }
    o.status = StatusCancelled
    o.events = append(o.events, OrderCancelled{OrderID: o.id})
    return nil
}

// Events are retrieved then purged after persistence
func (o *Order) PopEvents() []DomainEvent {
    events := o.events
    o.events = nil
    return events
}

Enter fullscreen mode Exit fullscreen mode

Notice what's absent: no database access, no HTTP calls, no external dependencies. The aggregate is pure Go. It expresses business rules and generates events — that's it. Persistence is someone else's problem.

Anti-Corruption Layer: isolating external APIs

Binance returns prices as strings: "4.00000000". OKEx uses a different format. Coinbase yet another. If you let these external formats leak into your domain, you have a problem: your model becomes dependent on the whims of three different exchanges.

The Anti-Corruption Layer (ACL) is the translation boundary. Outside: the exchange's model. Inside: your domain. The ACL translates, and your domain never hears about Binance.


// External model — what Binance actually sends
type binanceOrderBook struct {
    LastUpdateID int64      `json:"lastUpdateId"`
    Bids         [][]string `json:"bids"` // [["price", "qty"], ...]
    Asks         [][]string `json:"asks"`
}

// ACL: translates Binance model to domain
func (c *BinanceClient) GetOrderBook(ctx context.Context, pair TradingPair) (*domain.OrderBook, error) {
    raw, err := c.fetchRaw(ctx, pair.String())
    if err != nil {
        return nil, fmt.Errorf("binance order book %s: %w", pair, err)
    }
    return translateBinanceOrderBook(raw)
}

func translateBinanceOrderBook(raw *binanceOrderBook) (*domain.OrderBook, error) {
    bids := make([]domain.PriceLevel, 0, len(raw.Bids))
    for _, b := range raw.Bids {
        if len(b) != 2 {
            return nil, fmt.Errorf("unexpected bid format: %v", b)
        }
        price, err := decimal.NewFromString(b[0])
        if err != nil {
            return nil, fmt.Errorf("invalid bid price %q: %w", b[0], err)
        }
        qty, err := decimal.NewFromString(b[1])
        if err != nil {
            return nil, fmt.Errorf("invalid bid qty %q: %w", b[1], err)
        }
        bids = append(bids, domain.PriceLevel{
            Price:    domain.Price{Amount: price, Currency: "USDT"},
            Quantity: qty,
        })
    }
    // same for asks...
    return &domain.OrderBook{Bids: bids}, nil
}

Enter fullscreen mode Exit fullscreen mode

And for OKEx, the same interface, a different translation:


// External OKEx model — completely different format
type okexOrderBook struct {
    Data []struct {
        Asks      [][]string `json:"asks"` // [["price", "qty", "liquidated", "count"], ...]
        Bids      [][]string `json:"bids"`
        Timestamp string     `json:"ts"`
    } `json:"data"`
}

func (c *OKExClient) GetOrderBook(ctx context.Context, pair TradingPair) (*domain.OrderBook, error) {
    raw, err := c.fetchRaw(ctx, pair)
    if err != nil {
        return nil, fmt.Errorf("okex order book %s: %w", pair, err)
    }
    return translateOKExOrderBook(raw)
}

Enter fullscreen mode Exit fullscreen mode

Your trading code has no idea who's providing the order book. It calls an OrderBookProvider interface and receives a domain.OrderBook. If Binance changes its API from v3 to v4 with a new response format, only translateBinanceOrderBook changes. Zero impact on business logic.


// Interface defined by the domain — not by the exchanges
type OrderBookProvider interface {
    GetOrderBook(ctx context.Context, pair TradingPair) (*OrderBook, error)
}

// The trading service has no dependency on Binance, OKEx or Coinbase
type TradingService struct {
    orderBook  OrderBookProvider
    orderRepo  OrderRepository
}

Enter fullscreen mode Exit fullscreen mode

DDD and CQRS: how they fit together

If you've read the articles on CQRS aggregates and command handlers, you've already seen DDD in action without it being explicitly named.

DDD gives you the model: aggregates, Value Objects, domain events, bounded contexts. CQRS is the architectural pattern that exploits that model. The relationship is direct:

  • A Command expresses a business intent (PlaceOrder, CancelOrder)
  • The command handler loads the aggregate, calls a business method
  • The aggregate validates the invariant and emits a DomainEvent
  • The event is persisted, then propagated to read models (Portfolio, history)

// Command — business intent
type PlaceOrderCommand struct {
    Pair     TradingPair
    Side     Side
    Quantity decimal.Decimal
}

// Handler — orchestrates without business logic
func (h *PlaceOrderHandler) Handle(ctx context.Context, cmd PlaceOrderCommand) error {
    order, err := domain.NewOrder(cmd.Pair, cmd.Side, cmd.Quantity)
    if err != nil {
        return fmt.Errorf("invalid order: %w", err)
    }

    // Submit to exchange via ACL
    exchangeID, err := h.exchange.SubmitOrder(ctx, order)
    if err != nil {
        return fmt.Errorf("exchange submission: %w", err)
    }
    order.SetExchangeID(exchangeID)

    // Persist the aggregate and its events
    return h.orderRepo.Save(ctx, order)
}

Enter fullscreen mode Exit fullscreen mode

Without DDD, the command handler accumulates business logic. With DDD, it orchestrates: load, call, persist. The logic belongs to the aggregate.

What DDD doesn't solve

DDD adds complexity. Abstraction layers, interfaces everywhere, translations between models. On a simple CRUD service — user list, a few REST endpoints, no complex business rules — it's clear over-engineering.

For a crypto trading engine with business rules spanning multiple exchanges, invariants to maintain, divergent external formats, and logic that evolves with the market — it pays off. The cost of abstraction is offset by the ability to change one piece without bringing down the others.

The most honest test: if a domain expert — a trader — can read your code and recognize their business concepts, DDD is working. If your code talks about BinanceWebsocketMessageParser and RestAPIResponseDTO, you've let technology invade the domain.

Conclusion

DDD is not an architecture, it's a modeling philosophy. It says: code should speak the language of the people who understand the problem, not the language of the people who understand the technology. In a crypto trading service, that means Order, Position, TradingPair — not BinanceResponseWrapper.

Bounded contexts provide the structure. Aggregates provide consistency. Anti-Corruption Layers provide isolation. And when you add CQRS on top, you have a system where each part has a clear responsibility and explicit boundaries.

Next time you write a command handler, ask yourself: does this logic belong in the handler or in the aggregate? If the answer is "in the aggregate", you're doing DDD.