package main
import (
"os"
"runtime/debug"
"strconv"
)
func applyMemLimitFromEnv() {
v := os.Getenv("GOMEMLIMIT_BYTES")
if v == "" {
return
}
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n <= 0 {
return
}
debug.SetMemoryLimit(n)
}
In containerized environments, the Go runtime can benefit from knowing the memory budget. With Go 1.19+, debug.SetMemoryLimit lets you set a soft limit so the GC reacts more aggressively before the process gets killed by the OOM killer. I treat this as an operational tuning knob, not a magic fix: you still need to size caches and avoid leaks. The snippet below reads a byte value from GOMEMLIMIT_BYTES and applies it at startup. In production, I prefer using the standard GOMEMLIMIT env var when possible, but having an explicit hook can help when environments are inconsistent. The important part is observability: pair this with heap profiles and GC metrics so you understand the tradeoff between CPU and memory. Done carefully, this can improve stability for memory-constrained services.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
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.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
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
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
Share this code
Here's the card — post it anywhere.