Architecture & Hexagonal Layer Map
How modern enterprise microservices build upon go-app-kit and go-libs for zero-compromise reliability.
Core Business Accelerators
Seven hardened enterprise packages architected for zero data races, high concurrency, and direct statutory companion composition.
Guarantees at-least-once message delivery without dual-write race conditions using PostgreSQL row-level lease fencing.
- Contention-Free Polling:
SELECT ... FOR UPDATE SKIP LOCKEDallows $N$ worker replicas to poll without lock contention. - Lease-Token Fencing: UUID fencing tokens prevent lease clobbering by stale workers.
- Full-Jitter Exponential Backoff: Automatic retry policy with graceful transition of poison pills to
DEAD_LETTER. - Workerpool Integration: Directly powered by
go-libs/workerpoolfor bounded background concurrency.
Zero-disk in-memory HTML-to-PDF compilation engine with bundled statutory GST tax invoice and payment receipt templates.
- Headless Chromium Backend:
NewChromiumRendererdrives modern--headless=new --print-to-pdfwith loopback HTTP SSRF isolation and CSS@pageinjection. - Zero-Dep Pure-Go PDF 1.4:
NewPureGoRenderercompiles structured HTML (headings, tables, lists) into multi-page PDFs with zero host browser binaries. - Embedded GST Invoice: Compliant with Indian GST rules: Supplier/Buyer GSTINs, HSN/SAC codes, CGST/SGST/IGST breakdown.
- Bounded Subprocess Concurrency: Instance semaphores prevent resource exhaustion; legacy
WkhtmlRendererdeprecated under N+2 contract (remove in>= v0.10.0).
Unified multi-channel alert broker supporting synchronous and asynchronous delivery powered by bounded workerpools.
- SMTP Email: RFC 2822 / MIME multipart messaging (text/plain, text/html, attachments, and auth).
- Slack Integration: Structured webhook adapter with priority color bars (Critical, High, Normal, Low) and metadata fields.
- HMAC Webhooks:
X-Signature-SHA256tamper-proofing, timestamp binding, and constant-time signature verification. - Asynchronous Fan-out: Non-blocking broker dispatching via bounded worker queues keeping APIs sub-20ms.
Enterprise compliance audit logging with partitioned PostgreSQL persistence, append-only triggers, and JSON state diffing.
- Partitioned Storage: Range-partitioned by
created_atwith trigger-enforced append-only constraints. - JSON State Diffing:
ComputeDiffautomatically calculates field-level before-and-after property deltas. - Context Extraction: Automatically captures Actor identity, IP address, and comments without polluting domain interfaces.
- Asynchronous Ingestion: Decoupled queue prevents slow audit queries from slowing down business transactions.
High-throughput, low-memory streaming CSV export directly to io.Writer or HTTP response streams.
- Zero Memory Accumulation: Flushes rows iteratively; export million-row datasets without unbounded heap spikes.
- Excel UTF-8 BOM: Automatically prepends UTF-8 Byte Order Mark (
\xEF\xBB\xBF) for flawless Excel rendering. - Formula Injection Escaping: Sanitizes malicious Excel formulas (
=,+,-,@) preventing CSV injection attacks. - Flexible Delimiters: Configurable comma, semicolon, tab, and custom CRLF row endings.
Zero-leak object storage and HMAC-SHA256 presigned URL engine for archiving compiled PDF tax invoices and streaming CSV reports.
- Local Atomic Filesystem Store:
NewLocalStorestreams into sibling temp files with0600permissions, callsfsync, and atomically renames payload + metadata sidecar. - Path-Traversal Guard:
ValidateKeyrejects leading/trailing slashes,..traversal segments, backslashes, and null bytes. - SHA-256 Content Addressing: Automatically computes
SHA256Hexdigests and enforcesWithMaxObjectBytes/WithLocalMaxObjectByteslimits. - HMAC-SHA256 Presigned URLs:
PresignGet,PresignPut, and constant-timeVerifyPresignedURLverification across both memory and local disk stores.
Distributed lease-fenced periodic job runner for recurring billing cycles, GST aging snapshots, and PostgreSQL partition maintenance.
- Local OS
flock+ PID Store:NewFileLeaseStoreprovides crash-safe single-machine cross-process exclusion (LaunchAgent + desktop GUI/CLI) with0600lock files. - Distributed Lease Fencing:
LeaseStore.TryAcquireensures only one replica executes a scheduled job per lease TTL window. - Panic Recovery Barrier: Converts panics inside
JobFuncinto structured errors routed toWithErrorHandler. - Graceful Shutdown:
Start(ctx)halts tickers on context cancellation and waits for all in-flight jobs to drain.
Zero-dependency statutory Indian domain primitives (v0.4.0 ยท 127 exported symbols across 15 domain files): Verhoeff D5, GSTIN Mod-36, UPI VPAs, IFSC banking checks, and exact integer paise currency calculations.
- Verhoeff D5 Dihedral: Official UIDAI Aadhaar algorithm with checksum verification and privacy masking.
- GSTIN Mod-36: Statutory 15-character GST validation with check digit calculation across 38 states/UTs.
- UPI & Banking Primitives: UPI VPA handles, IFSC branch routing, MICR, and PAN legal classification.
- Zero-Dependencies: Pure domain primitives with zero third-party dependencies and sub-microsecond latency.
Interactive In-Browser Statutory Validator
Test statutory algorithms offline: GSTIN Mod-36 checksum, Aadhaar Verhoeff D5, PAN classification, and INR Paise calculation.
Reference Microservice Walkthrough
Complete production invoice processing pipeline combining all 6 modules located in examples/invoice_service.
Order & Invoicing Production Pipeline
Statement Coverage: 100.0%Demonstrates zero-compromise architectural decoupling: statutory checks run before database calls, documents render in memory without container disk I/O, events commit transactionally with PostgreSQL, and notifications queue asynchronously.
ValidateGSTIN and ValidateIFSC run in sub-microsecond time before any expensive DB or PDF processing.GenerateFromTemplate compiles tax invoice directly into a *bytes.Buffer with zero disk leaks.outboxStore.Insert commits the domain event in the same Postgres TX. No split-brain states.audit.RecordAsync writes partitioned, append-only logs with before/after state diffs.broker.SendAsync delivers customer email with PDF attachment and Slack ops alert via workerpool.Interactive Code Viewer
Production-ready idiomatic code patterns designed for clean integration and zero boilerplate.
package main
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
fintech "github.com/abeta-dev/go-fintech-india"
"github.com/abeta-dev/go-app-kit/audit"
"github.com/abeta-dev/go-app-kit/notifications"
"github.com/abeta-dev/go-app-kit/outbox"
"github.com/abeta-dev/go-app-kit/pdf"
)
func main() {
ctx := context.Background()
// 1. Statutory validation via companion go-fintech-india
buyerGSTIN := "29AAACI1681G1ZM"
if err := fintech.ValidateGSTIN(buyerGSTIN); err != nil {
panic("invalid statutory GSTIN: " + err.Error())
}
// 2. High-precision monetary computation in paise
taxable := fintech.NewMoneyFromRupees(15000) // โน15,000.00
cgst := taxable.Percentage(9.0) // 9% CGST (โน1,350.00)
sgst := taxable.Percentage(9.0) // 9% SGST (โน1,350.00)
total := taxable.Add(cgst).Add(sgst) // โน17,700.00
// 3. Compile in-memory GST Tax Invoice PDF
pdfBuf, _ := pdf.GenerateFromTemplate(pdf.GSTInvoiceTemplate, pdf.InvoiceData{
InvoiceNumber: "INV-2026-001",
InvoiceDate: time.Now().Format("2006-01-02"),
SupplierGSTIN: "27AAPFU0939F1ZV",
BuyerGSTIN: buyerGSTIN,
})
// 4. Transactional Outbox write in DB transaction (dual-write safety)
pool, _ := pgxpool.New(ctx, "postgres://localhost:5432/db")
store := outbox.NewPGStore(pool)
tx, _ := pool.Begin(ctx)
evt, _ := outbox.NewEvent("Invoice", "INV-2026-001", "Created", total)
_ = store.Insert(ctx, tx, *evt)
_ = tx.Commit(ctx)
// 5. Asynchronous audit & multi-channel notification dispatch
recorder, _ := audit.NewPGRecorder(audit.Config{DB: pool})
recorder.RecordAsync(audit.NewEvent(ctx, "INVOICE_CREATED", "Invoice", "INV-2026-001", nil, total))
broker := notifications.NewBroker(notifications.DefaultConfig())
_ = broker.SendAsync(ctx, notifications.Message{
Title: "Tax Invoice Ready: INV-2026-001",
Body: fmt.Sprintf("Invoice total %s generated successfully.", total.Format()),
Recipients: []string{"billing@enterprise.com"},
Channels: []notifications.Channel{notifications.ChannelEmail},
Attachments: []notifications.Attachment{
{Filename: "INV-2026-001.pdf", ContentType: "application/pdf", Data: pdfBuf.Bytes()},
},
})
}
package main
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/abeta-dev/go-app-kit/outbox"
)
func main() {
ctx := context.Background()
pool, _ := pgxpool.New(ctx, "postgres://user:pass@localhost:5432/app_db")
defer pool.Close()
// 1. Initialize PostgreSQL Outbox Store with lease fencing
store := outbox.NewPGStore(pool, outbox.WithLeaseDuration(30*time.Second))
// 2. Transactionally commit domain entity and outbox event in same DB transaction
tx, _ := pool.Begin(ctx)
defer tx.Rollback(ctx)
// ... execute business mutations on orders/invoices table ...
evt, _ := outbox.NewEvent("Invoice", "INV-2026-001", "InvoiceCreated", map[string]any{
"amount_paise": 1770059,
"customer_id": "CUST-8821",
})
if err := store.Insert(ctx, tx, *evt); err != nil {
return
}
_ = tx.Commit(ctx) // Atomic commit: zero phantom records
// 3. Autonomous background relay using SELECT ... FOR UPDATE SKIP LOCKED
relay, _ := outbox.NewRelay(outbox.RelayConfig{
Store: store,
Publisher: kafkaPublisher,
PollInterval: 500 * time.Millisecond,
BatchSize: 100,
})
go relay.Start(ctx)
}
package main
import (
"context"
"github.com/abeta-dev/go-app-kit/notifications"
)
func main() {
ctx := context.Background()
// 1. Initialize multi-channel broker with bounded workerpool
broker := notifications.NewBroker(notifications.DefaultConfig())
defer broker.Close()
// 2. Register senders: Email (SMTP), Slack, and HMAC-Signed Webhook
broker.RegisterSender(notifications.NewEmailSender(notifications.EmailConfig{
Host: "smtp.mail.com",
Port: 587,
User: "alerts@domain.com",
Pass: "secret",
From: "Billing ",
}))
broker.RegisterSender(notifications.NewSlackSender(notifications.SlackConfig{
WebhookURL: "https://hooks.slack.com/services/T00/B00/X00",
Channel: "#finance-alerts",
}))
// 3. Non-blocking asynchronous dispatch
_ = broker.SendAsync(ctx, notifications.Message{
Title: "Statutory Tax Invoice Ready: INV-2026",
Body: "Your invoice has been generated with GST breakdown.",
Priority: notifications.PriorityHigh,
Recipients: []string{"client-finance@corp.com"},
Channels: []notifications.Channel{notifications.ChannelEmail, notifications.ChannelSlack},
Attachments: []notifications.Attachment{
{Filename: "INV-2026.pdf", ContentType: "application/pdf", Data: pdfBytes},
},
})
}
package main
import (
"bytes"
"fmt"
"github.com/abeta-dev/go-app-kit/pdf"
)
func main() {
// Statutory B2B GST Invoice Data
invoiceData := pdf.InvoiceData{
InvoiceNumber: "INV-2026-0042",
InvoiceDate: "2026-09-20",
SupplierName: "Acme Cloud Technologies Pvt Ltd",
SupplierGSTIN: "27AAPFU0939F1ZV",
BuyerName: "Enterprise Retailers Ltd",
BuyerGSTIN: "29AAACI1681G1ZM",
Items: []pdf.InvoiceItem{
{
Description: "Cloud Infrastructure - September",
HSNSAC: "998313",
Quantity: 1,
UnitPrice: 15000.50,
CGSTRate: 9.0,
SGSTRate: 9.0,
},
},
}
// In-memory HTML-to-PDF compilation (Zero disk I/O)
pdfBuf, err := pdf.GenerateFromTemplate(pdf.GSTInvoiceTemplate, invoiceData,
pdf.WithPageSize("A4"),
pdf.WithOrientation("Portrait"),
pdf.WithMargins(10, 10, 10, 10),
)
if err != nil {
fmt.Printf("PDF generation failed: %v\n", err)
return
}
fmt.Printf("Generated %d bytes in-memory PDF buffer!\n", pdfBuf.Len())
}
package main
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/abeta-dev/go-app-kit/audit"
)
func main() {
ctx := context.Background()
pool, _ := pgxpool.New(ctx, "postgres://user:pass@localhost:5432/audit_db")
defer pool.Close()
// 1. Initialize asynchronous partitioned audit recorder
recorder, _ := audit.NewPGRecorder(audit.Config{
DB: pool,
Workers: 4,
QueueSize: 500,
})
defer recorder.Close()
// 2. Calculate field-level state diff (Old vs New)
oldState := map[string]any{"status": "DRAFT", "amount": 10000}
newState := map[string]any{"status": "ISSUED", "amount": 10000, "gstin": "27AAPFU0939F1ZV"}
// 3. Construct event with context-propagated actor & IP
ctx = audit.WithActor(ctx, "admin@corp.com")
ctx = audit.WithIP(ctx, "192.168.1.50")
event := audit.NewEvent(ctx, "INVOICE_STATE_CHANGE", "Invoice", "INV-100", oldState, newState)
recorder.RecordAsync(event)
}
package main
import (
"net/http"
"github.com/abeta-dev/go-app-kit/export"
fintech "github.com/abeta-dev/go-fintech-india"
)
type InvoiceExportRow struct {
ID string
BuyerGSTIN string
AmountPaise int64
}
func exportHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Header().Set("Content-Disposition", "attachment; filename=\"invoices.csv\"")
columns := []export.Column[InvoiceExportRow]{
{Header: "Invoice ID", Extractor: func(r InvoiceExportRow) string { return r.ID }},
{Header: "Buyer GSTIN", Extractor: func(r InvoiceExportRow) string { return r.BuyerGSTIN }},
{Header: "Amount (INR)", Extractor: func(r InvoiceExportRow) string {
return fintech.FormatINRPaise(r.AmountPaise)
}},
}
// Streams directly to ResponseWriter with Excel UTF-8 BOM and formula sanitization
streamer := export.NewCSVStreamer(w, columns, export.WithBOM(true))
defer streamer.Flush()
// Iteratively stream millions of rows without loading all into memory
for rows.Next() {
streamer.WriteRow(fetchNextInvoiceRow())
}
}
package invoice_service
import (
"context"
"github.com/abeta-dev/go-app-kit/audit"
"github.com/abeta-dev/go-app-kit/notifications"
"github.com/abeta-dev/go-app-kit/outbox"
"github.com/abeta-dev/go-app-kit/pdf"
fintech "github.com/abeta-dev/go-fintech-india"
)
// ProcessInvoice combines validation, PDF generation, outbox, audit, and notifications.
func (s *InvoiceService) ProcessInvoice(ctx context.Context, req InvoiceRequest) ([]byte, error) {
// Step 1: Statutory Validation (Fail-Fast via go-fintech-india)
if err := fintech.ValidateGSTIN(req.SupplierGSTIN); err != nil {
return nil, err
}
if err := fintech.ValidateGSTIN(req.BuyerGSTIN); err != nil {
return nil, err
}
// Step 2: Exact Money & Total Calculation
taxable := fintech.NewMoneyFromFloat(req.Amount)
cgst := taxable.Percentage(9.0)
sgst := taxable.Percentage(9.0)
total := taxable.Add(cgst).Add(sgst)
// Step 3: In-Memory PDF Document Compilation
pdfBuf, err := pdf.GenerateFromTemplate(pdf.GSTInvoiceTemplate, req.ToInvoiceData(total))
if err != nil {
return nil, err
}
// Step 4: Transactional Outbox (Postgres DB Transaction)
tx, err := s.pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
evt, _ := outbox.NewEvent("Invoice", req.ID, "InvoiceCreated", total)
if err := s.outboxStore.Insert(ctx, tx, *evt); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
// Step 5: Asynchronous Audit Logging
s.auditRecorder.RecordAsync(audit.NewEvent(ctx, "INVOICE_ISSUED", "Invoice", req.ID, nil, total))
// Step 6: Multi-Channel Alerts via Workerpool
_ = s.broker.SendAsync(ctx, notifications.Message{
Title: "Invoice Issued: " + req.ID,
Body: "Attached is your GST Tax Invoice.",
Recipients: []string{req.BuyerEmail},
Channels: []notifications.Channel{notifications.ChannelEmail, notifications.ChannelSlack},
Attachments: []notifications.Attachment{
{Filename: req.ID + ".pdf", ContentType: "application/pdf", Data: pdfBuf.Bytes()},
},
})
return pdfBuf.Bytes(), nil
}
Verified Statement Coverage
Continuous verification enforced by scripts/check_version.sh and scripts/check_coverage.sh.
| Package | Purpose | Dependencies | Statement Coverage |
|---|---|---|---|
export |
Low-memory streaming CSV exporter with Excel UTF-8 BOM & formula injection protection | Zero external | 100.0% |
notifications |
Multi-channel notification broker (SMTP Email, Brevo, WhatsApp, SMS, Slack, Webhook HMAC-SHA256) | go-libs/workerpool |
100.0% |
outbox |
PostgreSQL transactional outbox engine with row-level locked poller & lease fencing | jackc/pgx/v5 |
100.0% |
audit |
Partitioned PostgreSQL audit logging with automated JSON diffing, hash-chaining & append-only triggers | jackc/pgx/v5 |
100.0% |
pdf |
HTML-to-PDF compilation (headless Chromium, zero-dep pure-Go PDF 1.4, legacy wkhtmltopdf) & embedded GST templates | Pluggable / Pure Go / Chromium | 100.0% |
storage |
In-memory & local atomic 0600 filesystem object storage with SHA-256 digests, size limits & HMAC-SHA256 presigned URLs | Zero external | 100.0% |
scheduler |
Distributed & local OS flock/PID lease-fenced periodic job scheduler with panic recovery & graceful draining | Zero external | 100.0% |
examples/invoice_service |
Reference microservice with end-to-end integration test & exact paise math | Internal integration | 100.0% |
go-fintech-india Companion |
Independent statutory foundation (v0.4.0 ยท 127 exported symbols across 15 domain files: GSTIN, PAN, Aadhaar Verhoeff D5, IFSC, Money) | Zero external | 100.0% |
| Overall Repository | Verified Statement Coverage across core packages (Zero data races) | Go 1.26.0 | 100.0% |