Security in Go from cryptography to the supply chain: using AES-GCM and Argon2id from the crypto packages correctly, signing, verifying, and rotating JWTs with golang-jwt/v5, OAuth2/OIDC flows with golang.org/x/oauth2 and go-oidc including PKCE, secrets management with Vault and SOPS beyond the env-var pitfalls — and the supply chain locked down with govulncheck, GOPRIVATE, and SBOMs.
The "Kant & Curves" bookshop wants to save every sale as a log entry — and simultaneously send it to an analytics tool in real time. A naive approach would write the data twice: once for the log file, once for the stream. This is inefficient and error-prone. The solution: io.Reader/Writer compositors. They allow you to branch, connect, and duplicate data streams — without copying the data itself.
The foundation for understanding batch vs. stream architectures is laid out in Module 6: Data Architecture.
io.Pipe: Synchronous In-Memory Pipelines
An io.Pipe connects a PipeReader with a PipeWriter via a synchronous in-memory channel. When the writer writes, the reader can read the data — without any detour through memory. Perfect for situations where one goroutine generates data (Writer) and another consumes it (Reader), without the entire dataset having to land in memory.
The foundation: io.Pipe for communication between goroutines, without buffering in the traditional sense:
// internal/pipeline/pipe.go — io.Pipe as synchronous channel between producer and consumer
package pipeline
import (
"io"
"strings"
)
// ProcessStream reads from a Reader, transforms the data, and writes to PipeWriter
func ProcessStream(r io.Reader, w *io.PipeWriter, transform func(string) string) {
defer w.Close() // Mandatory! Otherwise the Reader hangs forever
buf := make([]byte, 4096)
for {
n, err := r.Read(buf)
if err != nil {
if err != io.EOF {
w.CloseWithError(err)
}
return
}
// Transform: e.g., to uppercase
transformed := transform(string(buf[:n]))
if _, err := w.Write([]byte(transformed)); err != nil {
w.CloseWithError(err)
return
}
}
}
// Example invocation: String Reader as source, transform to uppercase
func PipeExample() (string, error) {
pr, pw := io.Pipe()
// Producer goroutine
go ProcessStream(strings.NewReader("data-pipeline"), pw, strings.ToUpper)
// Consumer: read everything
buf := make([]byte, 4096)
n, err := pr.Read(buf)
if err != nil && err != io.EOF {
return "", err
}
return string(buf[:n]), nil
}
// Terminal: go run .
// → DATA-PIPELINE
Now the classic Unix tee command as a Go idiom: sending data to multiple writers simultaneously with io.MultiWriter:
// internal/pipeline/tee.go — Tee: writing data to multiple destinations simultaneously
package pipeline
import (
"bytes"
"fmt"
"io"
"os"
"strings"
)
// TeeWriter duplicates all data to multiple writers
func TeeWriter(writers ...io.Writer) io.Writer {
return io.MultiWriter(writers...)
}
// Example: writing to file AND stdout simultaneously
func TeeExample() error {
logFile, err := os.Create("pipeline.log")
if err != nil {
return err
}
defer logFile.Close()
// Tee: write to file AND stdout simultaneously
tee := TeeWriter(logFile, os.Stdout)
// Data source
src := strings.NewReader("Sales log: Book 978-0-06-231500-7\n")
// Copy: src -> tee (-> file AND stdout)
if _, err := io.Copy(tee, src); err != nil {
return err
}
return nil
}
// Terminal: go run .
// → Sales log: Book 978-0-06-231500-7
// (simultaneously written to pipeline.log)
For debugging pipelines, io.TeeReader is invaluable — it allows you to inspect a data stream without consuming it:
// internal/pipeline/debug.go — TeeReader for debugging data streams
package pipeline
import (
"bytes"
"fmt"
"io"
"strings"
)
// LogReader wraps a Reader and logs everything that passes through
func LogReader(name string, r io.Reader) io.Reader {
return io.TeeReader(r, &debugWriter{name: name})
}
type debugWriter struct {
name string
buf bytes.Buffer
}
func (w *debugWriter) Write(p []byte) (int, error) {
w.buf.Write(p)
fmt.Printf("[%s] received: %s", w.name, string(p))
return len(p), nil
}
func (w *debugWriter) String() string {
return w.buf.String()
}
// Example: data flow with logging
func TeeReaderExample() (string, error) {
// Original data
original := strings.NewReader("Important Data\n")
// Wrap with logging
logged := LogReader("Debug", original)
// Process (all data ends up in buffer)
var buf bytes.Buffer
if _, err := io.Copy(&buf, logged); err != nil {
return "", err
}
return buf.String(), nil
}
// Terminal: go run .
// → [Debug] received: Important Data
// → Important Data
⚠ Common mistake: Forgetting to call
io.PipeWriter.Close()when writing is done. The associatedPipeReaderthen waits forever for data and blocks the consuming goroutine. This manifests as a deadlock or timeout — and is responsible for most "my goroutine hangs" tickets in Go projects. Always placedefer w.Close()immediately after creating the Writer.
Check: Which statement about io.MultiWriter is correct?
Answer: MultiWriter writes the data to all writers simultaneously; an error in one writer breaks the entire write operation
io.MultiWriter calls Write(p) on all writers one after another — synchronously. If one of the writers fails (e.g., because the disk is full), Write returns that error and the remaining writers do not receive that data. The order is guaranteed, but there is no parallelism and no error tolerance.
Takeaways:
io.Pipe connects reader and writer synchronously via an in-memory channel — perfect for goroutine coordination without buffer bloat.io.MultiWriter duplicates all write operations to multiple writers — the Go equivalent of Unix tee.io.TeeReader reads data from a reader and simultaneously writes it to a writer — ideal for debugging pipelines.PipeWriter.Close() (or CloseWithError), otherwise the PipeReader hangs forever. A defer right when creating the writer reliably prevents this.In Module 7 (lessons 31-35), we learned how to use goroutines and channels for concurrent processing. But what happens when the producer generates data faster than the consumer can process it? Without a backpressure mechanism, the channel fills up to capacity — and the producer never blocks. The result: memory usage explodes, goroutines pile up, and the program crashes. Backpressure means: the producer is slowed down as soon as the consumer can't keep up.
The architectural decision between batch and stream is covered in Module 6: Data Architecture.
Channel Buffers Are Not a Cure-All
Buffered channels (make(chan T, 100)) can cushion short spikes, but they only obscure the backpressure problem. A buffered channel with size N can store a maximum of N items — once the buffer is full, the send on the channel blocks. Unbuffered channels (make(chan T)) have size 0 and block immediately on the first unread item. This is not a bug, but the desired behavior for backpressure: the producer is automatically throttled.
A classic scenario: a pipeline that reads files, processes them line by line, and saves the results. Without backpressure, the fast file-reading goroutine overwhelms the slow storage goroutine:
// internal/pipeline/backpressure.go — Pipeline with backpressure via unbuffered channels
package pipeline
import (
"bufio"
"context"
"fmt"
"os"
"strings"
"time"
)
// LineProcessor processes a line (simulates slow processing)
func LineProcessor(line string) string {
time.Sleep(50 * time.Millisecond) // Simulate CPU-intensive work
return strings.ToUpper(line)
}
// ProcessFileWithBackpressure reads a file line by line and processes with backpressure
func ProcessFileWithBackpressure(ctx context.Context, filename string) error {
// Context with timeout for entire pipeline
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Unbuffered channels enforce backpressure
lines := make(chan string) // Producer -> Processor
results := make(chan string) // Processor -> Consumer
// Consumer: save results (or output)
go func() {
defer close(results)
for result := range results {
fmt.Println("Saved:", result)
}
}()
// Processor: process lines
go func() {
defer close(results)
for line := range lines {
select {
case <-ctx.Done():
return
case results <- LineProcessor(line):
// Blocks if results is full — backpressure!
}
}
}()
// Producer: read file line by line
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
select {
case <-ctx.Done():
return ctx.Err()
case lines <- scanner.Text():
// Blocks if lines is full — backpressure propagates back!
}
}
close(lines)
return scanner.Err()
}
// Terminal: Create file with echo -e "Line 1\nLine 2\nLine 3" > input.txt, then go run .
// → Saved: LINE 1
// → Saved: LINE 2
// → Saved: LINE 3
Now the danger: What happens if the consumer leaves the pipeline early? Then the producer and processor goroutines hang forever because they're waiting for a receiver on their channels. The solution: Done channels and select statements in every goroutine:
// internal/pipeline/cancel.go — safely canceling a pipeline
package pipeline
import (
"context"
"fmt"
)
// SafePipeline demonstrates how to cleanly cancel goroutines
func SafePipeline(ctx context.Context, inputs []int) ([]int, error) {
// Channels for the pipeline
squared := make(chan int)
cubed := make(chan int)
results := make(chan int)
// Stage 1: Calculate square
go func() {
defer close(squared)
for _, n := range inputs {
select {
case <-ctx.Done():
return
case squared <- n * n:
}
}
}()
// Stage 2: Calculate cube
go func() {
defer close(cubed)
for n := range squared {
select {
case <-ctx.Done():
return
case cubed <- n * n * n:
}
}
}()
// Stage 3: Collect results
go func() {
defer close(results)
for n := range cubed {
select {
case <-ctx.Done():
return
case results <- n:
}
}
}()
// Collect results
var output []int
for result := range results {
output = append(output, result)
}
return output, ctx.Err()
}
func CancelExample() {
ctx, cancel := context.WithCancel(context.Background())
// Start pipeline
results := make(chan []int, 1)
go func() {
result, _ := SafePipeline(ctx, []int{1, 2, 3, 4, 5})
results <- result
}()
// Cancel after 100ms
time.AfterFunc(100*time.Millisecond, cancel)
// Wait for result (will never arrive due to cancel)
select {
case result := <-results:
fmt.Println("Result:", result)
case <-time.After(200 * time.Millisecond):
fmt.Println("Pipeline canceled — no goroutine leak!")
}
// → Pipeline canceled — no goroutine leak!
}
// Terminal: go run .
// → Pipeline canceled — no goroutine leak!
The critical pattern: Every goroutine in a pipeline must monitor the context or a done signal. Otherwise, goroutine leaks occur that slowly consume memory. Tools like go test -race find data races, but goroutine leaks often go unnoticed — until memory is exhausted.
⚠ Common mistake: In a multi-stage pipeline, only checking the context in the final stage. If stage 2 (processor) ignores the context but stage 3 (consumer) exits, stage 2 keeps writing to a channel that no one reads anymore. The stage 1 goroutine blocks on sending to stage 2 — all goroutines hang. EVERY stage must check the context or the done signal of the upstream channel.
Check: Which channel setup enforces backpressure most effectively?
Answer: Unbuffered channel — blocks on the first unread item
Unbuffered channels provide the strongest form of backpressure: every send operation blocks until the receiver is ready. This forces the producer to wait for the consumer. Buffered channels only hide the problem and can lead to memory explosion when producer and consumer have different speeds. The drop pattern loses data — that's not backpressure, that's data loss.
Takeaways:
Apache Kafka is the de-facto standard for distributed event streaming platforms. At the bookstore, Kafka could transport various events: orders, inventory movements, customer messages. But Kafka is complex — and the Go ecosystem offers two main libraries: sarama (github.com/IBM/sarama) and franz-go (github.com/twmb/franz-go). Both are based on the same Kafka protocol specification, but take different approaches.
In the context of event sourcing and CQRS, Kafka is often the central component. How events serve as the source of truth is explained in Module 11: Event Sourcing & CQRS.
franz-go: Modularity Over Simplicity
While sarama offers a monolithic API, franz-go is split into small, focused packages: github.com/twmb/franz-go/pkg/kgo for core functionality, github.com/twmb/franz-go/pkg/kmsg for message decoding, etc. This makes franz-go more modular and lightweight, but with a steeper learning curve. Sarama, on the other hand, offers an all-inclusive API that is sufficient for most use cases — at the cost of flexibility.
The classic approach: sarama as an all-in-one solution for producers and consumers:
// internal/kafka/sarama_producer.go — Producer with sarama
package kafka
import (
"context"
"fmt"
"log"
"github.com/IBM/sarama"
)
// NewSaramaProducer creates a synchronous producer
func NewSaramaProducer(brokers []string) (sarama.SyncProducer, error) {
config := sarama.NewConfig()
config.Producer.Return.Successes = true
config.Producer.RequiredAcks = sarama.WaitForAll // strongest consistency
config.Producer.Retry.Max = 3
return sarama.NewSyncProducer(brokers, config)
}
// PublishOrder publishes an order as a Kafka message
func PublishOrder(ctx context.Context, producer sarama.SyncProducer, topic string, orderJSON []byte) error {
msg := &sarama.ProducerMessage{
Topic: topic,
Key: sarama.StringEncoder("order_" + string(orderJSON[:8])), // first 8 bytes as key
Value: sarama.ByteEncoder(orderJSON),
}
// Synchronous send — blocks until confirmation
partition, offset, err := producer.SendMessage(msg)
if err != nil {
return fmt.Errorf("Kafka send failed: %w", err)
}
log.Printf("Message sent: topic=%s partition=%d offset=%d", topic, partition, offset)
return nil
}
// Terminal: Start Kafka locally, then go run .
// → Message sent: topic=orders partition=0 offset=42
Now the consumer with sarama — including consumer groups and rebalancing:
// internal/kafka/sarama_consumer.go — Consumer group with sarama
package kafka
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/IBM/sarama"
)
// NewSaramaConsumer creates a consumer in a consumer group
func NewSaramaConsumer(brokers []string, groupID string, topics []string) (sarama.ConsumerGroup, error) {
config := sarama.NewConfig()
config.Consumer.Group.Session.Timeout = 10 * time.Second
config.Consumer.Group.Heartbeat.Interval = 3 * time.Second
config.Consumer.Offsets.Initial = sarama.OffsetNewest // or OffsetOldest
config.Consumer.Return.Errors = true
return sarama.NewConsumerGroup(brokers, groupID, config)
}
// ConsumeOrders consumes orders from Kafka
func ConsumeOrders(ctx context.Context, consumer sarama.ConsumerGroup, topics []string) error {
handler := &OrderHandler{}
// Consumer groups must commit, otherwise rebalancing loops occur
for {
if err := consumer.Consume(ctx, topics, handler); err != nil {
// Rebalancing is normal — not an error!
if err == sarama.ErrClosedConsumerGroup {
return nil
}
log.Printf("Consumer error: %v", err)
}
// If returned due to error; wait briefly
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
}
}
}
type OrderHandler struct{}
func (h *OrderHandler) Setup(sarama.ConsumerGroupSession) error {
log.Println("Consumer Setup complete")
return nil
}
func (h *OrderHandler) Cleanup(sarama.ConsumerGroupSession) error {
log.Println("Consumer Cleanup")
return nil
}
func (h *OrderHandler) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
for message := range claim.Messages() {
log.Printf("Received: topic=%s partition=%d offset=%d key=%s value=%s\n",
message.Topic, message.Partition, message.Offset, string(message.Key), string(message.Value))
// Processing here...
// Important: manually commit, otherwise no progress!
session.MarkMessage(message, "")
}
return nil
}
func MainSarama() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
consumer, err := NewSaramaConsumer([]string{"localhost:9092"}, "bookstore-group", []string{"orders"})
if err != nil {
log.Fatal(err)
}
defer consumer.Close()
if err := ConsumeOrders(ctx, consumer, []string{"orders"}); err != nil {
log.Fatal(err)
}
}
// Terminal: Start Kafka with topic "orders", then go run .
// → Consumer Setup complete
// → Received: topic=orders partition=0 offset=42 key=order_... value={"id":123...}
Now the modern approach: franz-go with more control and batching:
// internal/kafka/franz_producer.go — Producer with franz-go and batching
package kafka
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
// NewFranzProducer creates a franz-go producer with batching
func NewFranzProducer(brokers []string, topic string) (*kgo.Client, error) {
// franz-go uses a functional options API
opts := []kgo.Opt{
kgo.SeedBrokers(brokers...),
kgo.DefaultProduceTopic(topic),
kgo.AllowAutoCreateTopics(),
kgo.MaxBufferRecords(1000), // how many messages in memory
kgo.BatchMaxBytes(1024 * 1024), // 1MB per batch
kgo.BatchMaxMs(100), // 100ms wait for batch filling
kgo.RequiredAcks(kgo.AllISRAcks), // strongest consistency
kgo.WithLogger(kgo.BasicLogger(log.New(os.Stdout, "franz: ", 0), kgo.LogLevelInfo)),
}
client, err := kgo.NewClient(opts...)
if err != nil {
return nil, err
}
return client, nil
}
// PublishOrdersBatch publishes multiple orders as a batch
func PublishOrdersBatch(ctx context.Context, client *kgo.Client, orders [][]byte) error {
var records []*kgo.Record
for i, orderJSON := range orders {
records = append(records, &kgo.Record{
Key: []byte(fmt.Sprintf("order_batch_%d", i)),
Value: orderJSON,
})
}
// Asynchronous send with batch optimization
client.ProduceSync(ctx, records...)
// Wait until all messages are confirmed
if err := client.Flush(ctx); err != nil {
return err
}
log.Printf("Batch with %d orders sent", len(orders))
return nil
}
// Terminal: Start Kafka, then go run .
// → franz: Client created
// → Batch with 10 orders sent
A critical point with Kafka: Rebalancing. When consumers are added or removed from a group, Kafka redistributes partitions. If the consumer hasn't committed the current offset, it starts from the last committed position upon reassignment — which can lead to duplicate processing. The solution: Manual or automatic commit with the right strategy:
// internal/kafka/franz_consumer.go — Consumer with franz-go and manual commit
package kafka
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
// NewFranzConsumer creates a franz-go consumer
func NewFranzConsumer(brokers []string, groupID string, topics []string) (*kgo.Client, error) {
opts := []kgo.Opt{
kgo.SeedBrokers(brokers...),
kgo.ConsumeTopics(topics...),
kgo.ConsumerGroup(groupID),
kgo.AutoCommitInterval(5 * time.Second), // auto commit every 5s
kgo.OnPartitionsAssigned(func(assigned map[string][]int32) {
log.Printf("Partitions assigned: %+v", assigned)
}),
kgo.OnPartitionsRevoked(func(revoked map[string][]int32) {
log.Printf("Partitions revoked: %+v", revoked)
// Here: save current state before rebalance completes
}),
kgo.DisableAutoCommit(), // we commit manually for more control
kgo.WithLogger(kgo.BasicLogger(log.New(os.Stdout, "franz-consumer: ", 0), kgo.LogLevelInfo)),
}
return kgo.NewClient(opts...)
}
func ConsumeWithFranz(ctx context.Context) error {
client, err := NewFranzConsumer([]string{"localhost:9092"}, "bookstore-franz-group", []string{"orders"})
if err != nil {
return err
}
defer client.Close()
for {
// Poll with 500ms timeout
fetches := client.PollFetches(ctx, 500)
if fetches.IsClientClosed() {
return nil
}
// Process all partitions
for _, fetch := range fetches {
for _, topicPartition := range fetch.TopicPartitions {
for _, record := range topicPartition.Records {
log.Printf("Received: topic=%s partition=%d offset=%d key=%s value=%s\n",
topicPartition.Topic, topicPartition.Partition, record.Offset,
string(record.Key), string(record.Value))
// Commit after successful processing
if err := client.CommitRecords(ctx, record); err != nil {
log.Printf("Commit failed: %v", err)
}
}
}
}
}
}
func MainFranz() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
if err := ConsumeWithFranz(ctx); err != nil {
log.Fatal(err)
}
}
// Terminal: Start Kafka with topic "orders", then go run .
// → franz-consumer: Partitions assigned: map[orders:[0]]
// → Received: topic=orders partition=0 offset=42 key=... value=...
⚠ Common mistake: Forgetting to commit offsets when working with consumer groups. Kafka then doesn't know which messages have already been processed. During rebalancing (e.g., because a consumer restarts), the consumer starts from the last committed position — and reprocesses all messages in between. With non-idempotent operations (e.g., money deductions), this leads to duplicate execution. Solution: Always explicitly commit (manually or automatically) and make operations idempotent.
Check: What advantage does franz-go have over sarama?
Answer: franz-go offers a modular API with better batch support and more detailed configuration
franz-go (
github.com/twmb/franz-go) was developed as a modern alternative to sarama and offers a modular architecture with packages likepkg/kgo,pkg/kmsg, etc. It has better performance characteristics, especially for batching, and more detailed configuration options. Sarama (github.com/IBM/sarama) is widely used but monolithic and partly outdated. For AI streaming data pipelines, examples can be found in our AI courses.
Takeaways:
github.com/IBM/sarama) is the established Go library — simple but monolithic.github.com/twmb/franz-go) is the modern alternative — modular, performant, with better batch support.Imagine the bookshop importing 10,000 new books from a CSV file. One insert per book would be inefficient: each roundtrip to the database server costs network latency, each query parse costs CPU, each transaction has overhead. The solution: Batch operations. PostgreSQL offers several approaches — and github.com/jackc/pgx/v5 makes them all accessible in Go.
The data architecture decision between batch and stream is covered in Module 6: Data Architecture.
pgx Batch vs. COPY: When to Use What?
pgx.Batch and pgx.COPY are both batch mechanisms, but for different scenarios: Batch sends multiple SQL statements as a single roundtrip and is perfect for complex inserts with generated values (serials, UUIDs). COPY is the PostgreSQL protocol for bulk data loading and is orders of magnitude faster — but only for simple data without transformations. If you're loading data from CSV or JSON, COPY is the first choice.
The simple entry: batch inserts with pgx.Batch:
// internal/db/batch.go — Batch Inserts with pgx
package db
import (
"context"
"fmt"
"log"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// Book defines our book structure
type Book struct {
ISBN string
Title string
Author string
PriceCents int64
Stock int32
}
// BatchInsertBooks inserts multiple books in a single transaction
func BatchInsertBooks(ctx context.Context, pool *pgxpool.Pool, books []Book) error {
// Create batch
batch := &pgx.Batch{}
for _, b := range books {
batch.Queue(`INSERT INTO books (isbn, title, author, price_cents, stock) VALUES ($1, $2, $3, $4, $5)`,
b.ISBN, b.Title, b.Author, b.PriceCents, b.Stock)
}
// Execute all statements in one roundtrip
br := pool.SendBatch(ctx, batch)
defer br.Close()
// Process results
for i := 0; i < batch.Len(); i++ {
_, err := br.Exec()
if err != nil {
return fmt.Errorf("batch error at index %d: %w", i, err)
}
}
log.Printf("Batch Insert: %d books inserted", len(books))
return nil
}
// Example call
func BatchExample() {
ctx := context.Background()
pool, _ := pgxpool.New(ctx, "postgres://user:password@localhost:5432/bookstore")
defer pool.Close()
books := []Book{
{ISBN: "978-0-06-231500-7", Title: "The Alchemist", Author: "Paulo Coelho", PriceCents: 1099, Stock: 10},
{ISBN: "978-0-316-76948-8", Title: "The Little Prince", Author: "Antoine de Saint-Exupery", PriceCents: 899, Stock: 15},
{ISBN: "978-0-19-923276-5", Title: "Faust Part One", Author: "Johann Wolfgang von Goethe", PriceCents: 699, Stock: 8},
}
_ = BatchInsertBooks(ctx, pool, books)
}
// Terminal: Start database, then go run .
// → Batch Insert: 3 books inserted
Now the turbo mode: COPY for maximum performance:
// internal/db/copy.go — COPY for bulk inserts
package db
import (
"bytes"
"context"
"fmt"
"log"
"strings"
"github.com/jackc/pgx/v5/pgxpool"
)
// CopyBooksFromCSV loads books from CSV data using COPY
func CopyBooksFromCSV(ctx context.Context, pool *pgxpool.Pool, csvData string) error {
// Split CSV into lines
lines := strings.Split(csvData, "\n")
if len(lines) < 2 {
return fmt.Errorf("no data to import")
}
// Skip header line
var buf bytes.Buffer
for _, line := range lines[1:] {
if line == "" {
continue
}
// CSV format: isbn,title,author,price_cents,stock
buf.WriteString(line + "\n")
}
// COPY command
copySQL := `COPY books (isbn, title, author, price_cents, stock) FROM STDIN WITH (FORMAT csv, DELIMITER ',')`
// Execute COPY
_, err := pool.CopyFrom(ctx, pgx.Identifier{"books"}, []string{"isbn", "title", "author", "price_cents", "stock"}, &buf)
if err != nil {
return fmt.Errorf("COPY failed: %w", err)
}
log.Printf("COPY: %d rows imported", len(lines)-1)
return nil
}
func CopyExample() {
ctx := context.Background()
pool, _ := pgxpool.New(ctx, "postgres://user:password@localhost:5432/bookstore")
defer pool.Close()
// Example CSV data
csvData := `isbn,title,author,price_cents,stock
978-0-06-231500-7,The Alchemist,Paulo Coelho,1099,10
978-0-316-76948-8,The Little Prince,Antoine de Saint-Exupery,899,15
978-0-19-923276-5,Faust Part One,Johann Wolfgang von Goethe,699,8`
_ = CopyBooksFromCSV(ctx, pool, csvData)
// → COPY: 3 rows imported
}
// Terminal: Start database, then go run .
// → COPY: 3 rows imported
The problem: COPY is fast — but when too much data is processed in a single transaction, the transaction can become too large and block the database. The solution: Transaction chunking — splitting large datasets into smaller batches, each processed in its own transaction:
// internal/db/chunked.go — Transaction chunking for large datasets
package db
import (
"context"
"fmt"
"log"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
const (
BatchSize = 1000 // Number of records per batch
MaxRetries = 3 // Maximum retries on errors
)
// ChunkedInsertBooks inserts books in chunks with separate transactions
func ChunkedInsertBooks(ctx context.Context, pool *pgxpool.Pool, books []Book) error {
for i := 0; i < len(books); i += BatchSize {
end := i + BatchSize
if end > len(books) {
end = len(books)
}
chunk := books[i:end]
for attempt := 0; attempt < MaxRetries; attempt++ {
if err := insertChunk(ctx, pool, chunk); err != nil {
if attempt == MaxRetries-1 {
return fmt.Errorf("chunk %d-%d failed: %w", i, end, err)
}
log.Printf("Retrying chunk %d-%d (attempt %d)", i, end, attempt+2)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second * time.Duration(attempt+1)):
}
} else {
break
}
}
}
log.Printf("Chunked Insert: %d books in %d chunks inserted", len(books), (len(books)+BatchSize-1)/BatchSize)
return nil
}
// insertChunk inserts a chunk in a single transaction
func insertChunk(ctx context.Context, pool *pgxpool.Pool, books []Book) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
batch := &pgx.Batch{}
for _, b := range books {
batch.Queue(`INSERT INTO books (isbn, title, author, price_cents, stock) VALUES ($1, $2, $3, $4, $5)`,
b.ISBN, b.Title, b.Author, b.PriceCents, b.Stock)
}
br := tx.SendBatch(ctx, batch)
defer br.Close()
for i := 0; i < batch.Len(); i++ {
_, err := br.Exec()
if err != nil {
return err
}
}
return tx.Commit(ctx)
}
// Example: Insert 5000 books in chunks
func ChunkedExample() {
ctx := context.Background()
pool, _ := pgxpool.New(ctx, "postgres://user:password@localhost:5432/bookstore")
defer pool.Close()
// Generate 5000 books
var books []Book
for i := 0; i < 5000; i++ {
books = append(books, Book{
ISBN: fmt.Sprintf("978-0-00-%05d-0", i),
Title: fmt.Sprintf("Book Number %d", i),
Author: "Unknown Author",
PriceCents: int64(i%2000 + 500),
Stock: int32(i % 100),
})
}
_ = ChunkedInsertBooks(ctx, pool, books)
}
// Terminal: Start database, then go run .
// → Chunked Insert: 5000 books in 5 chunks inserted
⚠ Common mistake: Choosing a batch size that's too large. A batch with 10,000 records may be fast in a local test, but in production it can cause various problems: transaction timeouts, lock contention, memory usage on the database server, or even hitting the maximum packet size (typically 1GB with PostgreSQL). The optimal batch size depends on your data and infrastructure. Start with 100-1000 records and measure performance under realistic conditions.
Check: When is COPY the better approach than Batch Insert?
Answer: When you're loading simple data from CSV or JSON into a table
COPY (
github.com/jackc/pgx/v5supports it viaCopyFrom) is a specialized protocol for bulk data loading. It's extremely fast (often 10-100x faster than batch inserts), but limited: no generated values, no complex transformations, no transaction logic. Batch inserts withpgx.Batchare more flexible but slower. For embedding pipelines, like in our AI applications, COPY is the standard choice.
Takeaways:
pgx.Batch is flexible (supports generated values, complex SQL) but slower than COPY.pgx.CopyFrom uses the PostgreSQL COPY protocol for maximum performance during bulk loading.Retrieval Augmented Generation (RAG) is the cornerstone of modern AI applications: instead of feeding the Large Language Model with all the world's knowledge, RAG searches for relevant documents in real time and provides them as context. The key to this: an embedding pipeline that transforms documents into vectors that can then be efficiently searched.
How embedding pipelines are architecturally embedded in AI systems is shown in the AI course on /aiml.
Embedding Pipeline: The Three Phases
An embedding pipeline goes through three phases: 1) Chunking — dividing documents into meaningful sections (e.g., sentences, paragraphs, code blocks), 2) Embedding — converting each chunk into a vector, 3) Storage — storing the vectors in a vector database (e.g., pgvector, Qdrant). The quality of the pipeline depends on the chunking strategy: chunks that are too large lose precision, chunks that are too small lose context.
Phase 1: Chunking — dividing documents into meaningful sections:
// internal/pipeline/chunker.go — Text chunking for embedding pipelines
package pipeline
import (
"bufio"
"bytes"
"context"
"io"
"strings"
)
// ChunkSize in tokens (Approximation: 1 token ≈ 4 characters for English text)
const ChunkSize = 1000
const ChunkOverlap = 200 // Overlap for context continuity
// TextChunker divides text into chunks with overlap
func TextChunker(text string, chunkSize, overlap int) []string {
tokens := tokenize(text)
var chunks []string
for i := 0; i < len(tokens); i += chunkSize - overlap {
end := i + chunkSize
if end > len(tokens) {
end = len(tokens)
}
chunk := strings.Join(tokens[i:end], " ")
chunks = append(chunks, chunk)
}
return chunks
}
// tokenize is a strong simplification
// In production: use the embedding API's tokenizer or a specialized library
func tokenize(text string) []string {
// Simplified: split on words and sentences
text = strings.ReplaceAll(text, "\n", " ")
text = strings.ReplaceAll(text, "\r", " ")
// Split on sentences (roughly)
sentences := strings.Split(text, ". ")
var tokens []string
for _, s := range sentences {
// Split on words
words := strings.Fields(s)
tokens = append(tokens, words...)
}
return tokens
}
// FileChunker reads files and divides them into chunks
func FileChunker(ctx context.Context, r io.Reader, chunkSize, overlap int) ([]string, error) {
// Read entire file (for small files)
data, err := io.ReadAll(r)
if err != nil {
return nil, err
}
// Split by lines (for structured text like code or logs)
var lines []string
scanner := bufio.NewScanner(bytes.NewReader(data))
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
// Remove empty lines
var nonEmptyLines []string
for _, line := range lines {
if strings.TrimSpace(line) != "" {
nonEmptyLines = append(nonEmptyLines, line)
}
}
// Group into chunks
return LineChunker(nonEmptyLines, chunkSize, overlap), nil
}
// LineChunker divides lines into chunks
func LineChunker(lines []string, linesPerChunk, overlap int) []string {
var chunks []string
for i := 0; i < len(lines); i += linesPerChunk - overlap {
end := i + linesPerChunk
if end > len(lines) {
end = len(lines)
}
chunk := strings.Join(lines[i:end], "\n")
chunks = append(chunks, chunk)
}
return chunks
}
// Terminal: Create file with text, then go run .
// → 3 chunks created
Phase 2: Generating embeddings with the OpenAI API:
// internal/pipeline/embedder.go — Embedding generation with OpenAI
package pipeline
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// Embedding model and API endpoint
const embeddingModel = "text-embedding-3-small"
const embeddingAPIURL = "https://api.openai.com/v1/embeddings"
// EmbedText generates an embedding for a text chunk
func EmbedText(ctx context.Context, apiKey, text string) ([]float32, error) {
// Rate limiting: max 100 requests per minute for text-embedding-3-small
time.Sleep(600 * time.Millisecond)
request := map[string]interface{}{
"input": text,
"model": embeddingModel,
}
jsonData, err := json.Marshal(request)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", embeddingAPIURL, bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
}
var result struct {
Data []struct {
Embedding []float32 `json:"embedding"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
if len(result.Data) == 0 {
return nil, fmt.Errorf("no embedding received")
}
return result.Data[0].Embedding, nil
}
// BatchEmbed generates embeddings for multiple chunks
func BatchEmbed(ctx context.Context, apiKey string, chunks []string) ([][]float32, error) {
// OpenAI supports up to 2048 chunks per request for text-embedding-3-*
const maxBatchSize = 2048
var allEmbeddings [][]float32
for i := 0; i < len(chunks); i += maxBatchSize {
end := i + maxBatchSize
if end > len(chunks) {
end = len(chunks)
}
batch := chunks[i:end]
request := map[string]interface{}{
"input": batch,
"model": embeddingModel,
}
jsonData, err := json.Marshal(request)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", embeddingAPIURL, bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
// Rate limiting
time.Sleep(600 * time.Millisecond)
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
}
var result struct {
Data []struct {
Embedding []float32 `json:"embedding"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
for _, d := range result.Data {
allEmbeddings = append(allEmbeddings, d.Embedding)
}
}
return allEmbeddings, nil
}
// Terminal: call with API key
// → 3 embeddings generated (1536 dimensions each)
Phase 3: Store vectors in pgvector for efficient similarity queries:
// internal/pipeline/vectorstore.go — Store vectors in PostgreSQL with pgvector
package pipeline
import (
"context"
"fmt"
"log"
"github.com/jackc/pgx/v5/pgxpool"
_ "github.com/pgvector/pgvector-go"
)
// DocumentChunk contains chunks with their metadata and embeddings
type DocumentChunk struct {
FileID string
ChunkIndex int
Content string
Embedding []float32
Metadata map[string]string
}
// StoreChunks stores chunks with embeddings in the database
func StoreChunks(ctx context.Context, pool *pgxpool.Pool, chunks []DocumentChunk) error {
// Transaction for atomic insert
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
// Create table if not exists
_, err = tx.Exec(ctx, `
CREATE TABLE IF NOT EXISTS document_chunks (
id SERIAL PRIMARY KEY,
file_id TEXT NOT NULL,
chunk_index INTEGER NOT NULL,
content TEXT NOT NULL,
metadata JSONB,
embedding vector(1536),
created_at TIMESTAMPTZ DEFAULT NOW()
)
`)
if err != nil {
return err
}
// Prepare batch insert
batch := &pgx.Batch{}
for _, chunk := range chunks {
batch.Queue(`INSERT INTO document_chunks (file_id, chunk_index, content, metadata, embedding) VALUES ($1, $2, $3, $4, $5)`,
chunk.FileID, chunk.ChunkIndex, chunk.Content, chunk.Metadata, chunk.Embedding)
}
// Execute
br := tx.SendBatch(ctx, batch)
defer br.Close()
for i := 0; i < batch.Len(); i++ {
_, err := br.Exec()
if err != nil {
return fmt.Errorf("batch error at chunk %d: %w", i, err)
}
}
return tx.Commit(ctx)
}
// SimilaritySearch searches for similar chunks
func SimilaritySearch(ctx context.Context, pool *pgxpool.Pool, queryEmbedding []float32, limit int) ([]DocumentChunk, error) {
rows, err := pool.Query(ctx, `
SELECT file_id, chunk_index, content, metadata
FROM document_chunks
ORDER BY embedding <=> $1
LIMIT $2
`, queryEmbedding, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var results []DocumentChunk
for rows.Next() {
var chunk DocumentChunk
if err := rows.Scan(&chunk.FileID, &chunk.ChunkIndex, &chunk.Content, &chunk.Metadata); err != nil {
return nil, err
}
results = append(results, chunk)
}
return results, rows.Err()
}
// Example: Complete pipeline from file to vectors to search
func FullPipelineExample() {
ctx := context.Background()
// 1. Database connection
pool, _ := pgxpool.New(ctx, "postgres://user:password@localhost:5432/vector_db")
defer pool.Close()
// 2. Chunk files
fileChunks, _ := FileChunker(ctx, strings.NewReader(`
This is the first paragraph of the document.
This is the second paragraph with important information.
And this is the third paragraph with the sought content.
`), ChunkSize, ChunkOverlap)
// 3. Generate embeddings (using mock API key for example)
// In production: use real API key
apiKey := "sk-..."
embeddings, _ := BatchEmbed(ctx, apiKey, fileChunks)
// 4. Store chunks with embeddings
var chunks []DocumentChunk
for i, chunk := range fileChunks {
chunks = append(chunks, DocumentChunk{
FileID: "test_document.txt",
ChunkIndex: i,
Content: chunk,
Embedding: embeddings[i],
Metadata: map[string]string{
"source": "example",
"type": "text",
},
})
}
_ = StoreChunks(ctx, pool, chunks)
// 5. Similarity search
query := "find important information"
queryEmbedding, _ := EmbedText(ctx, apiKey, query)
results, _ := SimilaritySearch(ctx, pool, queryEmbedding, 3)
fmt.Println("Search results:")
for i, result := range results {
fmt.Printf("%d. Chunk %d: %s\n", i+1, result.ChunkIndex, result.Content)
}
}
// Terminal: Start PostgreSQL with pgvector extension, then go run .
// → Search results:
// → 1. Chunk 1: This is the second paragraph with important information.
// → 2. Chunk 0: This is the first paragraph of the document.
// → 3. Chunk 2: And this is the third paragraph with the sought content.
The complete pipeline in a streaming processing context (e.g., for processing many files):
// internal/pipeline/streaming.go — Streaming pipeline for many files
package pipeline
import (
"context"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"sync"
)
// ProcessDirectory processes all files in a directory as a stream
func ProcessDirectory(ctx context.Context, pool *pgxpool.Pool, apiKey, dirPath string) error {
// File ID generator
fileCounter := 0
// Chunks channel for the pipeline
chunks := make(chan DocumentChunk, 100)
// Phase 1: Read files and chunk them (Producer)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
defer close(chunks)
if err := filepath.WalkDir(dirPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
// Only process text files
if !strings.HasSuffix(path, ".txt") && !strings.HasSuffix(path, ".md") {
return nil
}
fileID := fmt.Sprintf("file_%d", fileCounter)
fileCounter++
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
textChunks, err := FileChunker(ctx, file, ChunkSize, ChunkOverlap)
if err != nil {
return err
}
for i, chunk := range textChunks {
select {
case <-ctx.Done():
return ctx.Err()
case chunks <- DocumentChunk{
FileID: fileID,
ChunkIndex: i,
Content: chunk,
Metadata: map[string]string{
"filename": filepath.Base(path),
"path": path,
},
}:
}
}
return nil
}); err != nil {
log.Printf("Error processing %s: %v", dirPath, err)
}
}()
// Phase 2: Generate embeddings (Processor)
var mu sync.Mutex
var allChunks []DocumentChunk
const embeddingWorkers = 5
var embeddingWg sync.WaitGroup
for i := 0; i < embeddingWorkers; i++ {
embeddingWg.Add(1)
go func(workerID int) {
defer embeddingWg.Done()
for chunk := range chunks {
select {
case <-ctx.Done():
return
default:
}
// Generate embedding
embedding, err := EmbedText(ctx, apiKey, chunk.Content)
if err != nil {
log.Printf("Embedding error for %s:%d: %v", chunk.FileID, chunk.ChunkIndex, err)
continue
}
chunk.Embedding = embedding
mu.Lock()
allChunks = append(allChunks, chunk)
mu.Unlock()
}
}(i)
}
// Wait until all chunks are processed
wg.Wait()
close(chunks)
embeddingWg.Wait()
// Phase 3: Store all chunks
if err := StoreChunks(ctx, pool, allChunks); err != nil {
return err
}
log.Printf("Processed: %d chunks from %d files", len(allChunks), fileCounter)
return nil
}
// Terminal: Create directory with text files, then go run .
// → Processed: 42 chunks from 5 files
⚠ Common mistake: Not adapting the chunk size to the use case. Chunks that are too small (e.g., individual words) lose semantic context — the embedding can no longer grasp the meaning. Chunks that are too large (e.g., entire books) are too unspecific — the similarity query finds nothing precise. Typical chunk sizes for RAG: 256-2048 tokens, depending on the document type. Experimentation is mandatory! Also important: Overlap between chunks (20-50%) helps maintain context across chunk boundaries.
Check: Why is overlap between chunks important?
Answer: To ensure that no information is lost between chunks
Overlap between chunks (typically 20-50% of chunk size) ensures that information spanning the boundary between two chunks is not lost. If a sentence is split across two chunks, without overlap the semantic context would be lost. With overlap, the second part of the sentence appears at the beginning of the next chunk — the embedding can capture the complete context. This is especially critical for RAG pipelines to ensure search result quality. More details on embedding pipelines can be found in our AI courses.
Takeaways:
github.com/pgvector/pgvector-go) is ideal for PostgreSQL users; Qdrant is a standalone alternative.Course navigation: ← Module 18 · All 20 modules · Module 20 →