Senior Go Interview Prep - Core Go: https://go.vbloher.org/docs/01-core-go/ - Механика defer в Go: https://go.vbloher.org/docs/01-core-go/defer/ - Встраивание структур и интерфейсов (Embedding): https://go.vbloher.org/docs/01-core-go/embedding/ - Ошибки в Go: error, wrapping, errors.Is/As/Join: https://go.vbloher.org/docs/01-core-go/errors/ - Дженерики в Go (1.18+): https://go.vbloher.org/docs/01-core-go/generics/ - Интерфейсы в Go: https://go.vbloher.org/docs/01-core-go/interfaces/ - Устройство map в Go: https://go.vbloher.org/docs/01-core-go/maps/ - panic / recover: механика, раскрутка стека и runtime-паники: https://go.vbloher.org/docs/01-core-go/panic-recover/ - Указатели в Go: https://go.vbloher.org/docs/01-core-go/pointers/ - Рефлексия в Go (reflect): https://go.vbloher.org/docs/01-core-go/reflection/ - Внутреннее устройство слайсов в Go: https://go.vbloher.org/docs/01-core-go/slices/ - Строки, руны и байты в Go: https://go.vbloher.org/docs/01-core-go/strings-runes-bytes/ - Система типов Go: defined types, alignment, memory layout: https://go.vbloher.org/docs/01-core-go/type-system/ - Concurrency: https://go.vbloher.org/docs/02-concurrency/ - sync/atomic: https://go.vbloher.org/docs/02-concurrency/atomic/ - Буферизованные vs небуферизованные каналы: https://go.vbloher.org/docs/02-concurrency/buffered-unbuffered/ - Канал vs Mutex: когда что выбрать: https://go.vbloher.org/docs/02-concurrency/channel-vs-mutex/ - Каналы: устройство hchan: https://go.vbloher.org/docs/02-concurrency/channels/ - Утечки горутин, дедлоки, livelock, starvation: https://go.vbloher.org/docs/02-concurrency/common-leaks-deadlocks/ - sync.Cond: https://go.vbloher.org/docs/02-concurrency/cond/ - context: https://go.vbloher.org/docs/02-concurrency/context/ - Горутины: жизненный цикл, стоимость, стек: https://go.vbloher.org/docs/02-concurrency/goroutines-lifecycle/ - sync.Mutex и sync.RWMutex: https://go.vbloher.org/docs/02-concurrency/mutex-rwmutex/ - sync.Once: https://go.vbloher.org/docs/02-concurrency/once/ - Паттерны конкурентности: https://go.vbloher.org/docs/02-concurrency/patterns/ - Race Detector (гонки данных и -race): https://go.vbloher.org/docs/02-concurrency/race-detector/ - Планировщик GMP: https://go.vbloher.org/docs/02-concurrency/scheduler-gmp/ - select: https://go.vbloher.org/docs/02-concurrency/select/ - sync.WaitGroup: https://go.vbloher.org/docs/02-concurrency/waitgroup/ - Runtime и память: https://go.vbloher.org/docs/03-runtime-memory/ - Паттерны аллокаций и снижение давления на GC: https://go.vbloher.org/docs/03-runtime-memory/allocation-patterns/ - Escape Analysis: когда переменная убегает в кучу: https://go.vbloher.org/docs/03-runtime-memory/escape-analysis/ - Сборщик мусора Go: concurrent tri-color mark-sweep: https://go.vbloher.org/docs/03-runtime-memory/gc/ - Тюнинг GC: GOGC и GOMEMLIMIT: https://go.vbloher.org/docs/03-runtime-memory/gogc-gomemlimit/ - GOMAXPROCS: параллелизм планировщика и проблема контейнеров: https://go.vbloher.org/docs/03-runtime-memory/gomaxprocs/ - Утечки горутин (goroutine leaks): https://go.vbloher.org/docs/03-runtime-memory/goroutine-leaks/ - Утечки памяти в Go (несмотря на GC): https://go.vbloher.org/docs/03-runtime-memory/memory-leaks/ - Модель памяти Go (Go Memory Model): happens-before и синхронизация: https://go.vbloher.org/docs/03-runtime-memory/memory-model/ - pprof: профилирование CPU, памяти и блокировок в Go: https://go.vbloher.org/docs/03-runtime-memory/pprof/ - Execution Tracer и runtime/trace: тайминги вместо агрегатов: https://go.vbloher.org/docs/03-runtime-memory/runtime-tracing/ - Стек vs Куча: где живут данные в Go: https://go.vbloher.org/docs/03-runtime-memory/stack-vs-heap/ - Тестирование: https://go.vbloher.org/docs/04-testing/ - testify, assert/require и golden files: https://go.vbloher.org/docs/04-testing/assertions-testify/ - Бенчмарки в Go: https://go.vbloher.org/docs/04-testing/benchmarks/ - Покрытие, -race и флаки-тесты: https://go.vbloher.org/docs/04-testing/coverage-race/ - Нативный fuzzing в Go (1.18+): https://go.vbloher.org/docs/04-testing/fuzzing/ - Интеграционные тесты, testcontainers-go, TestMain: https://go.vbloher.org/docs/04-testing/integration-testcontainers/ - Моки, стабы и тестируемость: https://go.vbloher.org/docs/04-testing/mocks/ - Table-driven тесты, subtests и параллельность: https://go.vbloher.org/docs/04-testing/table-driven/ - Backend: https://go.vbloher.org/docs/05-backend/ - Аутентификация и авторизация: AuthN/AuthZ, сессии vs токены, RBAC/ABAC, API keys, mTLS, секреты: https://go.vbloher.org/docs/05-backend/auth-authz/ - Graceful Shutdown HTTP/gRPC сервера в Go: https://go.vbloher.org/docs/05-backend/graceful-shutdown/ - gRPC: типы RPC, интерсепторы, контекст, метаданные, error model: https://go.vbloher.org/docs/05-backend/grpc/ - JWT (JSON Web Token): https://go.vbloher.org/docs/05-backend/jwt/ - Middleware-паттерн в Go: https://go.vbloher.org/docs/05-backend/middleware/ - net/http: Server, Handler, ServeMux, таймауты, Client и контекст: https://go.vbloher.org/docs/05-backend/net-http/ - OAuth2: роли, grant types, OIDC, токены и типовые ошибки: https://go.vbloher.org/docs/05-backend/oauth2/ - OpenAPI/Swagger, code generation, contract-first vs code-first, валидация: https://go.vbloher.org/docs/05-backend/openapi/ - Protocol Buffers: схемы, wire format, эволюция и совместимость: https://go.vbloher.org/docs/05-backend/protobuf/ - REST: принципы, версионирование, идемпотентность, статусы, пагинация, ошибки: https://go.vbloher.org/docs/05-backend/rest/ - Сети и протоколы: https://go.vbloher.org/docs/06-networking/ - Пулы соединений: http.Transport, БД, утечки: https://go.vbloher.org/docs/06-networking/connection-pooling/ - DNS: записи, резолвинг, кэширование, DNS в Go: https://go.vbloher.org/docs/06-networking/dns/ - Версии HTTP: 1.1, 2, 3: https://go.vbloher.org/docs/06-networking/http-versions/ - TCP/IP: модель, транспорт и что важно бэкендеру: https://go.vbloher.org/docs/06-networking/tcp-ip/ - TLS: handshake, сертификаты, mTLS, производительность: https://go.vbloher.org/docs/06-networking/tls/ - UDP и надёжность поверх UDP: https://go.vbloher.org/docs/06-networking/udp/ - WebSocket: upgrade, фреймы, масштабирование: https://go.vbloher.org/docs/06-networking/websocket/ - Базы данных: https://go.vbloher.org/docs/07-databases/ - Пул соединений к PostgreSQL в Go: database/sql, pgx, pgxpool, PgBouncer: https://go.vbloher.org/docs/07-databases/connection-pooling-pgx/ - Взаимоблокировки (Deadlocks) в PostgreSQL: https://go.vbloher.org/docs/07-databases/deadlocks/ - Индексы в PostgreSQL: https://go.vbloher.org/docs/07-databases/indexes/ - Уровни изоляции транзакций в PostgreSQL: https://go.vbloher.org/docs/07-databases/isolation-levels/ - MVCC в PostgreSQL: версии строк, видимость, VACUUM и bloat: https://go.vbloher.org/docs/07-databases/mvcc/ - Обзор NoSQL и Redis: https://go.vbloher.org/docs/07-databases/nosql-redis/ - Партиционирование таблиц в PostgreSQL: https://go.vbloher.org/docs/07-databases/partitioning/ - Архитектура PostgreSQL: https://go.vbloher.org/docs/07-databases/postgresql-architecture/ - Планирование и оптимизация запросов в PostgreSQL: https://go.vbloher.org/docs/07-databases/query-planning/ - Репликация в PostgreSQL: https://go.vbloher.org/docs/07-databases/replication/ - Шардирование (горизонтальное масштабирование): https://go.vbloher.org/docs/07-databases/sharding/ - Транзакции в PostgreSQL и Go (database/sql, pgx): https://go.vbloher.org/docs/07-databases/transactions/ - Распределённые системы: https://go.vbloher.org/docs/08-distributed-systems/ - CAP теорема: https://go.vbloher.org/docs/08-distributed-systems/cap-theorem/ - Circuit Breaker: https://go.vbloher.org/docs/08-distributed-systems/circuit-breaker/ - Консенсус и Raft: репликация состояния в присутствии отказов: https://go.vbloher.org/docs/08-distributed-systems/consensus-raft/ - Модели согласованности: https://go.vbloher.org/docs/08-distributed-systems/consistency/ - Гарантии доставки сообщений: at-most-once / at-least-once / exactly-once: https://go.vbloher.org/docs/08-distributed-systems/delivery-guarantees/ - Eventual Consistency: https://go.vbloher.org/docs/08-distributed-systems/eventual-consistency/ - Идемпотентность в распределённых системах: https://go.vbloher.org/docs/08-distributed-systems/idempotency/ - Apache Kafka: https://go.vbloher.org/docs/08-distributed-systems/kafka/ - Transactional Outbox: https://go.vbloher.org/docs/08-distributed-systems/outbox/ - RabbitMQ: AMQP 0-9-1, маршрутизация, надёжность доставки и сравнение с Kafka: https://go.vbloher.org/docs/08-distributed-systems/rabbitmq/ - Ретраи: backoff, jitter, budgets и идемпотентность: https://go.vbloher.org/docs/08-distributed-systems/retries/ - Saga Pattern: https://go.vbloher.org/docs/08-distributed-systems/saga/ - Observability: https://go.vbloher.org/docs/09-observability/ - Grafana: https://go.vbloher.org/docs/09-observability/grafana/ - Метрики: RED, USE, Golden Signals: https://go.vbloher.org/docs/09-observability/metrics/ - OpenTelemetry: https://go.vbloher.org/docs/09-observability/opentelemetry/ - Prometheus: https://go.vbloher.org/docs/09-observability/prometheus/ - SLI / SLO / SLA: https://go.vbloher.org/docs/09-observability/slo-sli/ - Структурированное логирование (slog): https://go.vbloher.org/docs/09-observability/structured-logging/ - Distributed Tracing: https://go.vbloher.org/docs/09-observability/tracing/ - System Design: https://go.vbloher.org/docs/10-system-design/ - Analytics Pipeline: https://go.vbloher.org/docs/10-system-design/analytics-pipeline/ - Chat System: https://go.vbloher.org/docs/10-system-design/chat/ - Фреймворк System Design интервью: https://go.vbloher.org/docs/10-system-design/framework/ - Notification Service: https://go.vbloher.org/docs/10-system-design/notification-service/ - Order Service: https://go.vbloher.org/docs/10-system-design/order-service/ - Payment Service: https://go.vbloher.org/docs/10-system-design/payment-service/ - Rate Limiter: https://go.vbloher.org/docs/10-system-design/rate-limiter/ - URL Shortener: https://go.vbloher.org/docs/10-system-design/url-shortener/ - DevOps: https://go.vbloher.org/docs/11-devops/ - CI/CD: пайплайны, стадии, стратегии деплоя: https://go.vbloher.org/docs/11-devops/cicd/ - Облака (AWS / GCP) для бэкендера: https://go.vbloher.org/docs/11-devops/cloud-aws-gcp/ - Docker для Go-разработчика: https://go.vbloher.org/docs/11-devops/docker/ - GitHub Actions и GitLab CI: https://go.vbloher.org/docs/11-devops/github-gitlab-ci/ - Kubernetes для Go-разработчика: https://go.vbloher.org/docs/11-devops/kubernetes/ - Terraform / Infrastructure as Code: https://go.vbloher.org/docs/11-devops/terraform/ - Алгоритмы: https://go.vbloher.org/docs/12-algorithms/ - Типовые алгоритмические задачи и паттерны: https://go.vbloher.org/docs/12-algorithms/common-problems/ - Асимптотическая сложность (Big-O): https://go.vbloher.org/docs/12-algorithms/complexity/ - Структуры данных в Go: https://go.vbloher.org/docs/12-algorithms/data-structures/ - Специфика live-coding на Go: https://go.vbloher.org/docs/12-algorithms/go-specifics/ - Behavioral: https://go.vbloher.org/docs/13-behavioral/ - Конфликты, разногласия и работа со стейкхолдерами: https://go.vbloher.org/docs/13-behavioral/conflicts/ - Как проходит senior-интервью: этапы, оценка, оффер: https://go.vbloher.org/docs/13-behavioral/interview-flow/ - Лидерство и менторство: https://go.vbloher.org/docs/13-behavioral/leadership-mentoring/ - Типовые поведенческие вопросы для Senior: https://go.vbloher.org/docs/13-behavioral/senior-questions/ > Модуль: Тестирование · Уровень: Middle+/Senior ## TL;DR Бенчмарк — функция `BenchmarkXxx(b *testing.B)`, в которой измеряемый код крутится `b.N` раз; рантайм сам подбирает `b.N`, увеличивая его, пока время прогона не станет статистически осмысленным (по умолчанию ~1s, регулируется `-benchtime`). `b.ResetTimer()` отсекает дорогой setup, `b.ReportAllocs()` (или флаг `-benchmem`) добавляет аллокации/op и байты/op. Результаты нестабильны от прогона к прогону — сравнивать релизы нужно через `benchstat` по нескольким прогонам (`-count`), а не по одному числу. Главные ошибки измерений: мёртвый код, который выкидывает компилятор (нужен sink), setup внутри измеряемого цикла, шумная машина, и интерпретация одного прогона как истины. ## Теория ### Анатомия бенчмарка ```go func BenchmarkFib(b *testing.B) { for i := 0; i < b.N; i++ { Fib(20) } } ``` Запуск: `go test -bench=. -benchmem`. Вывод: ``` BenchmarkFib-10 254679 4712 ns/op 0 B/op 0 allocs/op ``` - `-10` — `GOMAXPROCS`. - `254679` — итоговое `b.N`. - `ns/op` — наносекунд на операцию (общее время / b.N). - `B/op`, `allocs/op` — при `-benchmem` или `b.ReportAllocs()`. ### Как подбирается `b.N` Рантайм запускает бенчмарк с `b.N=1`, замеряет, и итеративно увеличивает `b.N` (округляя вверх до «красивых» чисел), пока суммарное время не достигнет `-benchtime` (дефолт `1s`). Поэтому **тело должно быть идемпотентно относительно b.N** — нельзя полагаться на конкретное значение N. Можно задать число итераций явно: `-benchtime=1000x` (ровно 1000 раз) или `-benchtime=5s` (по времени). ### ResetTimer / StopTimer / StartTimer Таймер включён с начала функции. Дорогой setup исказит результат: ```go func BenchmarkProcess(b *testing.B) { data := generateLargeDataset() // дорого, НЕ должно попасть в замер b.ResetTimer() // обнуляем таймер и счётчики аллокаций for i := 0; i < b.N; i++ { Process(data) } } ``` Если setup нужен на каждой итерации: ```go for i := 0; i < b.N; i++ { b.StopTimer() input := freshInput() b.StartTimer() Process(input) } ``` `StopTimer`/`StartTimer` в горячем цикле дороги сами по себе и шумят — по возможности готовьте все входы заранее (срез из b.N элементов) и `ResetTimer` один раз. ### ReportAllocs и память ```go func BenchmarkConcat(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { var s string for j := 0; j < 100; j++ { s += "x" } _ = s } } ``` `allocs/op` часто важнее `ns/op`: аллокации создают давление на GC, которое проявляется под нагрузкой, а не в микробенче. Снижение аллокаций — типичная цель senior-оптимизации (sync.Pool, переиспользование буферов, `strings.Builder`, предвыделение слайсов с `make([]T, 0, n)`). ### Sink: борьба с устранением мёртвого кода Компилятор может выкинуть вычисление, результат которого не используется, или заинлайнить и соптимизировать так, что замеряется ничто: ```go var sink int // пакетный уровень — компилятор не докажет, что не используется func BenchmarkParse(b *testing.B) { var r int for i := 0; i < b.N; i++ { r = Parse(input) // присваиваем } sink = r // выносим наружу — мешаем DCE } ``` В Go 1.24+ есть `b.Loop()`, который решает это идиоматичнее: ```go func BenchmarkParse(b *testing.B) { for b.Loop() { Parse(input) // результат не выкинется, setup до Loop не замеряется } } ``` `b.Loop()` гарантирует, что аргументы и результаты функции не будут устранены оптимизатором, и сам отбивает таймер: код до первого `b.Loop()` не измеряется, что снимает нужду в `ResetTimer` для setup. ### Параллельные бенчмарки ```go func BenchmarkCacheGet(b *testing.B) { c := NewCache() b.RunParallel(func(pb *testing.PB) { for pb.Next() { c.Get("key") // измеряем под конкуренцией } }) } ``` `RunParallel` распределяет `b.N` итераций по `GOMAXPROCS` горутинам — для измерения contention (мьютексы, sync.Map, атомики). Регулируется `b.SetParallelism`. ### Custom metrics ```go b.ReportMetric(float64(bytesProcessed)/b.Elapsed().Seconds(), "B/s") b.ReportMetric(float64(rows)/float64(b.N), "rows/op") ``` ### benchstat: правильное сравнение Один прогон ничего не доказывает — шум CPU, частоты, GC. Алгоритм: ```bash go test -bench=BenchmarkX -benchmem -count=10 ./... > old.txt # внесли изменение go test -bench=BenchmarkX -benchmem -count=10 ./... > new.txt benchstat old.txt new.txt ``` `benchstat` (golang.org/x/perf/cmd/benchstat) считает медиану/среднее, разброс (±%) и **p-value** (значимо ли отличие). Если в колонке стоит `~`, разница статистически не значима — «оптимизация» в пределах шума. ### Профилирование через бенчмарки ```bash go test -bench=BenchmarkX -cpuprofile=cpu.prof -memprofile=mem.prof -benchmem go tool pprof cpu.prof # top, list Func, web go tool pprof -alloc_space mem.prof ``` Бенчмарк — удобный воспроизводимый драйвер для pprof: даёт стабильную нагрузку. `-blockprofile`, `-mutexprofile` — для contention. ## Подводные камни / gotchas - **Один прогон ≠ результат.** Используйте `-count` + `benchstat`. Без статистики «стало на 3% быстрее» — самообман. - **Мёртвый код / DCE.** Без sink или `b.Loop()` компилятор может удалить измеряемую работу → нереально маленькие `ns/op` (доли наносекунды). - **Setup в цикле.** Аллокация входных данных внутри `for i:=0; i