devHọc Dev
EN
Bài học

Tuần 2 - Ngày 7: AWS SDK for Go v2, Lambda bằng Go, container nhỏ, cross-compile và `pprof`

Tuần 2 – Ngày 7

Bài này gộp 4 chủ đề: AWS SDK for Go v2 (config, client, paginator, lỗi, retry, test), Lambda bằng Go trên runtime provided.al2023, Build container nhỏ (multi-stage, distroless/scratch) và cross-compile, Profiling với pprof và tinh chỉnh runtime trong container.

Mục tiêu học tập

  • Khởi tạo AWS SDK for Go v2 đúng cách: một lần, dùng lại client, truyền ctx cho từng lời gọi
  • Dùng paginator, xử lý lỗi bằng smithy.APIError và lỗi có kiểu của từng service, cấu hình retry và timeout
  • Viết code dùng SDK mà vẫn unit test được bằng interface nhỏ ở phía dùng
  • Viết, build và deploy Lambda bằng Go trên provided.al2023 (arm64, bootstrap, -tags lambda.norpc); hiểu vì sao không còn go1.x
  • Viết Dockerfile multi-stage ra image vài MB, chọn giữa scratch và distroless, chạy non-root
  • Cross-compile cho linux/arm64 (Graviton), nhúng phiên bản vào binary
  • Thu và đọc profile CPU, heap, goroutine bằng pprof mà không mở lỗ hổng ra internet
  • Biết GOMAXPROCS, GOMEMLIMIT và PGO ảnh hưởng gì khi chạy trong container

Phần 1: AWS SDK for Go v2

1. Cài đặt và khởi tạo

SDK v1 (github.com/aws/aws-sdk-go) đã hết hỗ trợ từ 31/07/2025. Dùng v2: mỗi service là một module riêng, chỉ kéo về những gì bạn dùng.

go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/service/dynamodb
go get github.com/aws/aws-sdk-go-v2/service/s3
go get github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue
func newClients(ctx context.Context) (*dynamodb.Client, *s3.Client, error) {
	cfg, err := config.LoadDefaultConfig(ctx,
		config.WithRegion("ap-southeast-1"), // bỏ qua để lấy từ AWS_REGION / ~/.aws/config
	)
	if err != nil {
		return nil, nil, fmt.Errorf("load aws config: %w", err)
	}
	return dynamodb.NewFromConfig(cfg), s3.NewFromConfig(cfg), nil
}
  • LoadDefaultConfig dò credential theo chuỗi mặc định của AWS SDK: biến môi trường, file ~/.aws/config và ~/.aws/credentials (kể cả profile SSO, assume role), web identity token (IRSA trên EKS), credential của ECS task role, và IMDS trên EC2. Code giống nhau ở máy dev, ECS, Lambda; chỉ môi trường khác nhau.
  • Tạo client một lần lúc khởi động và dùng lại: client an toàn khi dùng đồng thời từ nhiều goroutine và giữ connection pool. Tạo client mới cho mỗi request làm mất keep-alive và tốn thời gian.
  • Field trong input là con trỏ để phân biệt "không đặt" với zero value. Dùng helper aws.String("x"), aws.Int32(25), aws.ToString(p) (trả "" nếu nil).
  • Tuỳ chọn theo từng lời gọi qua functional option: client.GetObject(ctx, in, func(o *s3.Options) { o.Region = "us-east-1" }).
  • Chạy với DynamoDB Local hoặc LocalStack: dynamodb.NewFromConfig(cfg, func(o *dynamodb.Options) { o.BaseEndpoint = aws.String("http://localhost:8000") }).

2. Đọc, ghi DynamoDB và paginator

type OrderItem struct {
	PK        string `dynamodbav:"pk"`
	SK        string `dynamodbav:"sk"`
	Customer  string `dynamodbav:"customer"`
	Total     int64  `dynamodbav:"total"`
	CreatedAt string `dynamodbav:"created_at"`
}

func (s *Store) Create(ctx context.Context, it OrderItem) error {
	av, err := attributevalue.MarshalMap(it)
	if err != nil {
		return fmt.Errorf("marshal order %s: %w", it.PK, err)
	}
	_, err = s.db.PutItem(ctx, &dynamodb.PutItemInput{
		TableName:           aws.String(s.table),
		Item:                av,
		ConditionExpression: aws.String("attribute_not_exists(pk)"), // không ghi đè đơn đã có
	})
	if err != nil {
		var ccf *types.ConditionalCheckFailedException
		if errors.As(err, &ccf) {
			return order.ErrAlreadyExists
		}
		return fmt.Errorf("put order %s: %w", it.PK, err)
	}
	return nil
}

API trả kết quả theo trang (ListObjectsV2, Query, Scan) có paginator sẵn. Kết hợp với iterator (Ngày 2) để người gọi duyệt từng phần tử mà không cần biết về trang:

func (s *Store) ObjectKeys(ctx context.Context, bucket, prefix string) iter.Seq2[string, error] {
	return func(yield func(string, error) bool) {
		p := s3.NewListObjectsV2Paginator(s.s3, &s3.ListObjectsV2Input{
			Bucket: aws.String(bucket),
			Prefix: aws.String(prefix),
		})
		for p.HasMorePages() {
			page, err := p.NextPage(ctx)
			if err != nil {
				yield("", err)
				return
			}
			for _, obj := range page.Contents {
				if !yield(aws.ToString(obj.Key), nil) {
					return
				}
			}
		}
	}
}

for key, err := range store.ObjectKeys(ctx, "invoices", "2026/11/") {
	if err != nil {
		return err
	}
	fmt.Println(key)
}

3. Lỗi, retry, timeout

Mọi lỗi từ client được bọc trong *smithy.OperationError (tên service, operation). Lỗi do service trả về thoả interface smithy.APIError; lỗi đã được mô hình hoá có kiểu riêng trong package types của service.

import (
	"github.com/aws/smithy-go"
	awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
	s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
)

out, err := s.s3.GetObject(ctx, &s3.GetObjectInput{Bucket: &bucket, Key: &key})
if err != nil {
	var nsk *s3types.NoSuchKey
	if errors.As(err, &nsk) {
		return nil, ErrInvoiceNotFound // lỗi có kiểu: rõ ràng nhất
	}
	var ae smithy.APIError
	if errors.As(err, &ae) && ae.ErrorCode() == "AccessDenied" {
		return nil, fmt.Errorf("check task role policy: %w", err)
	}
	var re *awshttp.ResponseError
	if errors.As(err, &re) {
		s.logger.Error("s3 get failed", "request_id", re.ServiceRequestID(), "err", err)
	}
	return nil, fmt.Errorf("get invoice %s: %w", key, err)
}
defer out.Body.Close() // Body là stream: luôn đóng
  • Retry mặc định: retry.Standard, tối đa 3 lần thử, backoff tối đa 20 giây, có token bucket hạn chế retry khi lỗi dồn dập. Lỗi throttling và lỗi mạng tạm thời được retry tự động; bạn không cần tự viết vòng retry quanh lời gọi SDK.
  • Nâng số lần thử:
    cfg, err := config.LoadDefaultConfig(ctx, config.WithRetryer(func() aws.Retryer {
    	return retry.AddWithMaxAttempts(retry.NewStandard(), 5)
    }))
    
    Cảnh báo: retry.AddWithMaxAttempts(..., 0) nghĩa là retry không giới hạn, dễ thành vòng lặp tốn tiền.
  • Timeout đặt bằng context cho từng lời gọi: ctx, cancel := context.WithTimeout(ctx, 2*time.Second). Khi context bị huỷ, SDK dừng và không retry nữa.

4. Unit test code dùng SDK

Đừng fake cả *dynamodb.Client (hàng chục method). Khai báo interface ở phía dùng, đúng chữ ký method của client, chỉ gồm những gì bạn gọi:

type dynamoAPI interface {
	PutItem(ctx context.Context, in *dynamodb.PutItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error)
	GetItem(ctx context.Context, in *dynamodb.GetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error)
}

type Store struct {
	db    dynamoAPI // *dynamodb.Client thoả interface này một cách ngầm định
	table string
}

type fakeDynamo struct {
	putErr error
	puts   []*dynamodb.PutItemInput
}

func (f *fakeDynamo) PutItem(_ context.Context, in *dynamodb.PutItemInput, _ ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error) {
	f.puts = append(f.puts, in)
	return &dynamodb.PutItemOutput{}, f.putErr
}

func (f *fakeDynamo) GetItem(context.Context, *dynamodb.GetItemInput, ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error) {
	return &dynamodb.GetItemOutput{}, nil
}

func TestCreate_Duplicate(t *testing.T) {
	f := &fakeDynamo{putErr: &types.ConditionalCheckFailedException{}}
	s := &Store{db: f, table: "orders"}
	err := s.Create(t.Context(), OrderItem{PK: "o-1"})
	if !errors.Is(err, order.ErrAlreadyExists) {
		t.Fatalf("err = %v, want ErrAlreadyExists", err)
	}
}

Kiểm tra thêm các lời gọi thật (điều kiện, index, quyền IAM) bằng integration test với DynamoDB Local hoặc tài khoản test, tách bằng build tag (Ngày 5).


Phần 2: Lambda bằng Go

1. Runtime: chỉ còn provided.al2023

Go biên dịch ra binary nên Lambda chạy Go trên OS-only runtime (họ provided). Theo bảng runtime của Lambda tại thời điểm viết (11/2026):

RuntimeHệ điều hànhTrạng thái
provided.al2023Amazon Linux 2023Được hỗ trợ, dự kiến deprecate 30/06/2029
provided.al2Amazon Linux 2Đã deprecate từ 31/07/2026; chặn tạo mới từ 29/07/2027
go1.xAmazon LinuxĐã deprecate từ 08/01/2024; chặn cập nhật từ 31/08/2027

So với go1.x, runtime provided hỗ trợ arm64 (Graviton), binary nhỏ hơn và invoke nhanh hơn một chút. Chuyển từ go1.x không cần sửa code, chỉ đổi cách build và runtime. (Tài liệu AWS hiện gọi loại function này là "Lambda Event Functions"; nội dung bài vẫn dùng "Lambda function".)

2. Handler

package main

import (
	"context"
	"encoding/json"
	"log/slog"
	"os"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
)

type app struct {
	store  *Store
	logger *slog.Logger
}

// Xử lý batch SQS; chỉ báo lại message lỗi để SQS không gửi lại cả batch.
func (a *app) handle(ctx context.Context, ev events.SQSEvent) (events.SQSEventResponse, error) {
	var resp events.SQSEventResponse
	for _, msg := range ev.Records {
		var it OrderItem
		err := json.Unmarshal([]byte(msg.Body), &it)
		if err == nil {
			err = a.store.Create(ctx, it)
		}
		if err != nil {
			a.logger.ErrorContext(ctx, "process message", "message_id", msg.MessageId, "err", err)
			resp.BatchItemFailures = append(resp.BatchItemFailures,
				events.SQSBatchItemFailure{ItemIdentifier: msg.MessageId})
		}
	}
	return resp, nil
}

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	// Khởi tạo một lần trong init phase, dùng lại qua nhiều lần invoke.
	cfg, err := config.LoadDefaultConfig(context.Background())
	if err != nil {
		logger.Error("load aws config", "err", err)
		os.Exit(1)
	}
	a := &app{
		store:  &Store{db: dynamodb.NewFromConfig(cfg), table: os.Getenv("ORDERS_TABLE")},
		logger: logger,
	}
	lambda.Start(a.handle)
}
  • Chữ ký handler hợp lệ: 0-2 đối số (nếu 2 thì đầu tiên là context.Context), 0-2 giá trị trả về (nếu có thì cuối cùng là error). Kiểu input/output phải dùng được với encoding/json. Package events có sẵn kiểu cho SQS, SNS, S3, API Gateway, EventBridge...
  • Khởi tạo client SDK ngoài handler (trong main trước lambda.Start, hoặc init): execution environment được dùng lại giữa các lần invoke nên client và connection pool được dùng lại.
  • Không lưu dữ liệu của request trong biến toàn cục: lần invoke sau (có thể của người dùng khác) sẽ thấy.
  • ctx mang deadline của lần invoke: truyền nó vào mọi lời gọi SDK để dừng trước khi Lambda timeout. Package lambdacontext lấy request ID của lần invoke.
  • Partial batch response (BatchItemFailures) chỉ có tác dụng khi event source mapping bật ReportBatchItemFailures.

3. Build và deploy dạng .zip

GOOS=linux GOARCH=arm64 CGO_ENABLED=0 \
  go build -tags lambda.norpc -trimpath -ldflags="-s -w" -o bootstrap ./cmd/order-worker
zip order-worker.zip bootstrap

aws lambda create-function --function-name order-worker \
  --runtime provided.al2023 --handler bootstrap \
  --architectures arm64 \
  --role arn:aws:iam::111122223333:role/order-worker-role \
  --zip-file fileb://order-worker.zip
  • File thực thi phải tên bootstrap và nằm ở gốc file zip. Giá trị --handler không quan trọng với runtime provided (quy ước đặt bootstrap).
  • -tags lambda.norpc bỏ phần RPC của aws-lambda-go, phần chỉ cần cho runtime go1.x đã deprecate; binary nhỏ hơn.
  • --architectures mặc định là x86_64; với arm64 phải đặt rõ, và GOARCH phải khớp. Sai kiến trúc thì function lỗi ngay khi khởi động.
  • Với AWS SAM: Runtime: provided.al2023, Handler: bootstrap, và Metadata: BuildMethod: go1.x. Ở đây go1.x là tên cách build của SAM, không phải runtime cũ; dễ nhầm khi review template.

4. Lambda dạng container image

Base image public.ecr.aws/lambda/provided:al2023 đã có sẵn Runtime Interface Emulator để test local:

FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -tags lambda.norpc -o /out/main ./cmd/order-worker

FROM public.ecr.aws/lambda/provided:al2023
COPY --from=build /out/main ./main
ENTRYPOINT ["./main"]
docker buildx build --platform linux/arm64 --provenance=false -t order-worker:dev .
docker run -d -p 9000:8080 --entrypoint /usr/local/bin/aws-lambda-rie order-worker:dev ./main
curl "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"Records":[]}'

Với container image, binary đặt tên gì cũng được. --provenance=false cần để image tương thích với Lambda khi build bằng buildx.


Phần 3: Container nhỏ và cross-compile

1. Dockerfile multi-stage cho service trên ECS/EKS

# syntax=docker/dockerfile:1
FROM --platform=$BUILDPLATFORM golang:1.27 AS build
ARG TARGETOS TARGETARCH VERSION=dev
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
    go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" \
    -o /out/orders-api ./cmd/orders-api

FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/orders-api /orders-api
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/orders-api"]
docker buildx build --platform linux/arm64,linux/amd64 --build-arg VERSION=1.4.2 -t orders-api:1.4.2 .

Giải thích các lựa chọn:

  • FROM --platform=$BUILDPLATFORM: stage build chạy native trên máy build, Go cross-compile sang TARGETARCH. Nhanh hơn nhiều so với build trong giả lập QEMU.
  • Copy go.mod/go.sum và go mod download trước khi copy source: layer dependency được cache, sửa code không tải lại module. Cache mount giữ cả build cache của Go giữa các lần build.
  • CGO_ENABLED=0: binary tĩnh, không phụ thuộc libc, chạy được trên image không có libc.
  • -trimpath: bỏ đường dẫn máy build khỏi binary. -ldflags="-s -w": bỏ bảng symbol và DWARF, binary nhỏ hơn; stack trace khi panic và pprof vẫn có tên hàm vì Go dùng bảng thông tin riêng của runtime.
  • Image cuối chỉ chứa binary: không shell, không package manager, bề mặt tấn công nhỏ.
Image cuốiCó gìKhi nào dùng
scratchKhông có gìMuốn nhỏ tuyệt đối và tự lo CA certificate, tzdata, user
gcr.io/distroless/static-debian13 (khoảng 2 MiB)CA certificates, tzdata, /etc/passwd (có user nonroot), /tmp; không glibcMặc định cho binary Go tĩnh
gcr.io/distroless/base-debian13Như trên + glibc, libsslBinary dùng cgo
alpineShell, apk, muslCần shell để debug; chấp nhận bề mặt tấn công lớn hơn

Bẫy khi dùng scratch:

  • Không có CA certificate: mọi lời gọi HTTPS (kể cả tới AWS API) lỗi x509: certificate signed by unknown authority. Phải copy /etc/ssl/certs/ca-certificates.crt từ stage build.
  • Không có tzdata: time.LoadLocation("Asia/Ho_Chi_Minh") lỗi. Sửa bằng import _ "time/tzdata" hoặc build với -tags timetzdata để nhúng tzdata vào binary.
  • Không có shell: health check dạng CMD-SHELL curl ... trong ECS không chạy được. Dùng health check của ALB/target group, hoặc thêm lệnh con orders-api healthcheck vào chính binary.

2. Cross-compile và nhúng phiên bản

go tool dist list | grep linux                      # các cặp GOOS/GOARCH hỗ trợ
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o dist/orders-cli-linux-arm64 ./cmd/orders-cli
GOOS=darwin GOARCH=arm64 go build -o dist/orders-cli-darwin-arm64 ./cmd/orders-cli
GOOS=windows GOARCH=amd64 go build -o dist/orders-cli.exe ./cmd/orders-cli
  • Cross-compile thuần Go chỉ cần đặt GOOS/GOARCH; không cần máy đích. Có cgo thì cần toolchain C cho nền tảng đích, phức tạp hơn nhiều: lý do chính để giữ CGO_ENABLED=0 cho service và CLI.
  • Graviton (arm64) thường rẻ hơn x86 cùng cấu hình; với Go, chuyển sang arm64 thường chỉ là đổi GOARCH.
  • Nhúng phiên bản: -ldflags "-X main.version=1.4.2" gán vào biến var version = "dev" trong package main. Khi build trong git repo, Go còn tự nhúng commit (vcs.revision, vcs.time, vcs.modified), đọc bằng debug.ReadBuildInfo(); build trong Docker mà không copy .git thì không có thông tin này, nên vẫn cần -X.

Phần 4: pprof và runtime trong container

1. Mở endpoint pprof an toàn

import _ "net/http/pprof" đăng ký handler vào http.DefaultServeMux. Nếu service phục vụ public cũng dùng DefaultServeMux (ví dụ http.ListenAndServe(":8080", nil)), profile và thông tin nội bộ bị lộ ra internet. Cách an toàn là một server admin riêng, chỉ nghe trên localhost:

import "net/http/pprof"

func startAdmin(logger *slog.Logger) {
	mux := http.NewServeMux()
	mux.HandleFunc("/debug/pprof/", pprof.Index) // heap, goroutine, allocs, goroutineleak...
	mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
	mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
	mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
	srv := &http.Server{Addr: "127.0.0.1:6060", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			logger.Error("admin server", "err", err)
		}
	}()
}

Truy cập từ máy dev qua ECS Exec hoặc SSM port forwarding, không mở port trong security group.

2. Thu và đọc profile

# CPU 30 giây từ service đang chạy
go tool pprof -http=:8081 'http://localhost:6060/debug/pprof/profile?seconds=30'
# Bộ nhớ đang dùng
go tool pprof -http=:8081 http://localhost:6060/debug/pprof/heap
# Goroutine gom theo stack: tìm hàng nghìn goroutine kẹt cùng một dòng
curl -s 'http://localhost:6060/debug/pprof/goroutine?debug=1' | head -50
# Từ Go 1.27: goroutine bị chặn vĩnh viễn (rò)
curl -s 'http://localhost:6060/debug/pprof/goroutineleak?debug=1'
# Profile từ benchmark
go test -run='^$' -bench=. -cpuprofile=cpu.out -memprofile=mem.out ./money
go tool pprof -top cpu.out
ProfileTrả lời câu hỏiGhi chú
profile (CPU)Thời gian CPU tiêu vào đâu?Lấy mẫu trong seconds giây
heapBộ nhớ đang giữ (inuse) và đã cấp phát (alloc) ở đâu?Chọn sample_index=inuse_space hoặc alloc_space
goroutineGoroutine đang làm gì, có bị kẹt không?debug=1 gom theo stack, debug=2 in từng goroutine
goroutineleakGoroutine nào không bao giờ được đánh thức nữa?Chính thức từ Go 1.27
mutex, blockTranh chấp lock, chờ đồng bộ ở đâu?Phải bật bằng runtime.SetMutexProfileFraction, runtime.SetBlockProfileRate

Trong giao diện web (-http), từ Go 1.26 view mặc định là flame graph: chiều ngang là tỷ lệ thời gian/bộ nhớ, đọc từ dưới lên theo stack. Trong chế độ dòng lệnh, top xem hàm tốn nhất, list TênHàm xem từng dòng code.

Quy trình tối ưu: đo (benchmark, profile) → tìm điểm nóng → sửa một chỗ → đo lại bằng benchstat. Đừng tối ưu theo cảm giác.

3. Runtime trong container

Thiết lậpÝ nghĩaKhuyến nghị
GOMAXPROCSSố thread chạy code Go đồng thờiTừ Go 1.25 tự theo CPU limit của cgroup trên Linux; thường không cần đặt
GOMEMLIMIT (Go 1.19+)Giới hạn mềm bộ nhớ: GC chạy thường xuyên hơn khi heap tiến gần mức nàyĐặt khoảng 80-90% memory limit của container để giảm nguy cơ bị OOM kill; runtime không tự suy ra giá trị này từ cgroup như với GOMAXPROCS (theo release notes tới Go 1.27)
GOGCTần suất GC theo tỷ lệ tăng heap (mặc định 100)Thường giữ mặc định khi đã đặt GOMEMLIMIT
PGO (Go 1.21+)Tối ưu theo profile CPU thậtLưu một CPU profile từ production thành default.pgo trong thư mục package main; go build tự dùng

Từ Go 1.26, Green Tea GC được bật mặc định, giảm chi phí GC cho chương trình cấp phát nhiều; phần lớn service không cần chỉnh gì để hưởng lợi.


Câu hỏi ôn tập

  1. Vì sao nên tạo dynamodb.Client một lần lúc khởi động thay vì trong mỗi request?

    Xem đáp án

    Client an toàn khi dùng đồng thời và giữ connection pool; tạo mới mỗi request làm mất keep-alive (thêm TLS handshake), tốn CPU và thời gian dò credential. Trong Lambda, tạo ở init phase còn giúp các lần invoke sau trên cùng execution environment dùng lại client.

  2. Viết đoạn code phân biệt ConditionalCheckFailedException với các lỗi khác khi PutItem.

    Xem đáp án

    var ccf *types.ConditionalCheckFailedException; if errors.As(err, &ccf) { return order.ErrAlreadyExists }, các lỗi khác wrap thêm ngữ cảnh và trả lên. Lỗi có kiểu của từng service nằm trong package types của service đó; lỗi chung dùng smithy.APIError và ErrorCode().

  3. Đồng nghiệp bọc mỗi lời gọi DynamoDB trong vòng lặp retry 5 lần tự viết. Góp ý gì?

    Xem đáp án

    SDK đã retry lỗi tạm thời (throttling, lỗi mạng) với backoff và token bucket, mặc định 3 lần thử. Vòng tự viết nhân số lần thử lên (5 × 3), làm tình trạng throttling tệ hơn. Nếu cần nhiều lần thử hơn, cấu hình retryer của SDK (retry.AddWithMaxAttempts), và đặt timeout bằng context.

  4. Làm sao unit test Store.Create mà không gọi AWS và không fake toàn bộ client?

    Xem đáp án

    Khai báo interface ở phía dùng chỉ gồm method cần (ví dụ PutItem) với đúng chữ ký của client, gồm cả optFns ...func(*dynamodb.Options). *dynamodb.Client thoả nó ngầm định; trong test, dùng fake trả lỗi hay kết quả mong muốn.

  5. Function Go vẫn dùng runtime go1.x. Cần đổi những gì để chuyển sang provided.al2023 trên arm64?

    Xem đáp án

    Code handler không cần sửa. Build với GOOS=linux GOARCH=arm64, đặt tên binary bootstrap ở gốc zip, nên thêm -tags lambda.norpc; đổi runtime sang provided.al2023 và --architectures arm64. provided.al2 không còn là lựa chọn vì đã deprecate từ 31/07/2026.

  6. Template SAM có BuildMethod: go1.x và Runtime: provided.al2023. Có mâu thuẫn không?

    Xem đáp án

    Không. BuildMethod: go1.x là tên cách build của SAM CLI (biên dịch Go thành bootstrap), còn runtime thực tế là provided.al2023. Chỉ có Runtime: go1.x mới là runtime đã deprecate.

  7. Service chạy trên image scratch gọi DynamoDB lỗi x509: certificate signed by unknown authority. Nguyên nhân và hai cách sửa?

    Xem đáp án

    scratch không có CA certificate nên không xác thực được chứng chỉ TLS của AWS. Sửa: copy file CA bundle từ stage build vào image, hoặc chuyển sang gcr.io/distroless/static-debian13 đã có sẵn CA certificate (và tzdata, user nonroot).

  8. Vì sao Dockerfile dùng FROM --platform=$BUILDPLATFORM golang:1.27 cho stage build khi build image arm64 trên máy x86?

    Xem đáp án

    Để stage build chạy native trên kiến trúc của máy build và để Go cross-compile sang TARGETARCH. Không có nó, buildx chạy toàn bộ quá trình biên dịch trong giả lập QEMU, chậm hơn nhiều lần.

  9. Vì sao không nên import _ "net/http/pprof" trong service public dùng http.ListenAndServe(":8080", nil)?

    Xem đáp án

    Import đó đăng ký /debug/pprof/ vào DefaultServeMux, chính là handler mà ListenAndServe(..., nil) phục vụ, nên ai cũng xem được profile, cmdline và có thể chạy profile CPU tốn tài nguyên. Dùng server admin riêng nghe trên 127.0.0.1 với mux riêng.

  10. Container giới hạn 1 GiB bộ nhớ bị OOM kill khi tải tăng đột biến dù heap trung bình chỉ 400 MiB. Thiết lập runtime nào giúp, và đặt thế nào?

    Xem đáp án

    GOMEMLIMIT, ví dụ khoảng 900MiB: khi heap tiến gần giới hạn, GC chạy thường xuyên hơn thay vì để heap phình theo GOGC tới mức vượt limit của container. Đây là giới hạn mềm, không thay thế việc tìm nguyên nhân bằng profile heap nếu bộ nhớ thật sự cần vượt mức đó.

Bài tập thực hành

Bài 1: Store DynamoDB có test

Viết Store với Create (có ConditionExpression) và Get, dùng interface dynamoAPI. Unit test bằng fake cho ca tạo trùng; integration test (build tag integration) với DynamoDB Local.

Đầu ra mong đợi: go test ./... không cần mạng; go test -tags=integration ./store pass khi DynamoDB Local đang chạy.

Bài 2: Lambda worker arm64

Đóng gói handler SQS ở Phần 2 thành Lambda provided.al2023 arm64 bằng SAM hoặc AWS CLI, nối với một hàng đợi SQS có bật ReportBatchItemFailures. Gửi 10 message, trong đó 2 message JSON hỏng.

Đầu ra mong đợi: 8 đơn được ghi; 2 message hỏng quay lại hàng đợi (rồi vào DLQ sau số lần nhận tối đa); log JSON có message_id của 2 message lỗi.

Bài 3: Image nhỏ đa kiến trúc

Viết Dockerfile multi-stage cho orders-api, build cho linux/amd64 và linux/arm64, nhúng VERSION. Thêm endpoint /version trả phiên bản và vcs.revision (nếu có).

Đầu ra mong đợi: kích thước image cuối (ghi lại con số); docker run chạy với user nonroot; thử đổi image cuối sang scratch và ghi lại lỗi gặp phải khi gọi HTTPS.

Bài 4: Tìm điểm nóng bằng pprof

Thêm admin server pprof vào orders-api. Tạo tải bằng công cụ như hey hoặc vegeta vào GET /orders/{id}, thu CPU profile 30 giây và heap profile.

Đầu ra mong đợi: ảnh chụp flame graph; 3 hàm tốn CPU nhất; một cải tiến cụ thể được đo lại bằng benchmark và benchstat.

Tài liệu tham khảo


Bài tiếp theo →