go
28 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package deps
import (
"net"
"net/http"
"time"
)
func NewHTTPClient() *http.Client {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 200,
MaxIdleConnsPerHost: 50,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 3 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
return &http.Client{
Timeout: 5 * time.Second,
Transport: tr,
}
}
1 file · go
Explain with highlit
The default http.Client is deceptively easy to misuse. I always set a request timeout (either via client.Timeout for simple cases or context.WithTimeout per request) and I tune the Transport so we reuse connections aggressively without leaking idle sockets forever. MaxIdleConnsPerHost is a common bottleneck for high fan-out services, and TLSHandshakeTimeout prevents handshake stalls from pinning goroutines. For services that call other services, these settings reduce tail latency and help avoid cascading failures. The biggest win is consistency: if every outbound call has a timeout, your service won’t hang just because a dependency is slow. Pair this with retries and you get predictable behavior.
Related snips
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
typescript
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
typescript
reliability
retry
by codesnips
2 tabs
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
ruby
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
rails
performance
streaming
by codesnips
3 tabs
ruby
Rails.application.configure do
config.after_initialize do
Bullet.enable = true
Bullet.alert = false
Bullet.bullet_logger = true
Bullet.console = true
N+1 query detection with Bullet gem
rails
performance
activerecord
by Alex Kumar
2 tabs
ruby
json.array! @posts do |post|
json.cache! ['v1', post], expires_in: 1.hour do
json.id post.id
json.title post.title
json.excerpt post.excerpt
json.published_at post.published_at
Fragment caching for expensive JSON serialization
rails
caching
performance
by Alex Kumar
1 tab
Share this code
Here's the card — post it anywhere.