How to optimise image uploads in Go: 3.2 MB in, 149 KB out
People keep asking how Grit shrinks an upload by 22x, and whether they can have it without Grit. You can: it is about two hundred lines of Go. But almost none of the saving comes from where everybody reaches first, and I have the measurements to prove it.

The most common question I get about Grit is not about the admin panel or the generator. It is this:
I uploaded a photo from my phone, it was 1.2 MB, and the file in the bucket is 90 KB. What is doing that? Can I do it in my own Go project?
Yes. It is one package, no system dependencies, and the whole thing is about two hundred lines. This post is that package, built up from nothing, with measurements at each step and the traps that cost me real afternoons.
But I want to lead with the measurement, because it changed how I build these pipelines and it contradicts the first thing almost everybody tries.
The number first
A 12 megapixel photo, the size a phone camera actually produces, through the default pipeline:
source: 3340 KB 4032x3024 (3.26 MB)primary: 141 KB 1600x1200 image/jpegthumb: 9 KB 400x400 image/jpegstored: 149 KB for everythingratio: 22.3x smaller than the sourcetime: 659ms
Two caveats so you can trust the rest of the post. That source image is synthetic, gradients plus per-pixel noise, which compresses worse than a real photograph. And 659ms is the pure-Go backend on a laptop, single image, cold. Both numbers are conservative rather than flattering.
Conservative by a knowable amount, as it turns out. The same pipeline measured on a real 6.08 MB camera photo, 4000x3000, lands on 141 KB plus a 9 KB thumbnail: the same output, byte for byte, as my synthetic one. That makes sense once you see why. The output size is a function of the output pixels and the quality, not of what the input weighed. Which means the honest headline ratio on a real photo is 41x, not 22x, and my noisy test image was only ever making the input harder.
Where the saving actually comes from
Here is the part worth the price of admission. When people set out to shrink uploads, they reach for the quality slider. JPEG quality 90 down to 82, maybe 75, and then they argue in the pull request about whether 75 is visibly worse.
I measured each lever on its own: same source image, same encoder.
| What I changed | Result | Saving |
|---|---|---|
| Nothing (source, q90, 4032px) | 3340 KB | |
| Quality only: q90 to q82, full 4032px kept | 3020 KB | 10% |
| Resize only: down to 1600px, quality left at q90 | 242 KB | 93% |
| Both | 141 KB | 96% |
| Both, plus a 400px thumbnail | 149 KB | 96% |
Read those two middle rows again.
The quality slider, on its own, bought me 10%. The resize, on its own and with quality untouched, bought me 93%.
This is obvious once you see it and invisible until you do. JPEG compression is already very good at the per-pixel level, so leaning on it harder has diminishing returns almost immediately. But file size scales with pixel count, and pixel count scales with the square of the dimension. Going from 4032px wide to 1600px wide is not a 60% reduction in pixels. It is 84%, because both axes shrink at once: 12.2 megapixels becomes 1.9.
So the lesson, if you take one thing from this post:
Resizing is the optimisation. Quality is the rounding error.
And the corollary, which is the actual bug in most hand-rolled upload code: storing a 4032px image at all is the mistake. Nobody's browser will ever draw it. A 1600px image covers a 2x retina display at a typical content width. Everything above that is bytes you pay to store, pay to transfer, and the browser throws away during layout.
While I was measuring this I also tried the thing you are not supposed to do, which is force a photograph down a lossless path:
photo forced to lossless WebP 2471 KB 1600x1200
Resized to 1600px, same as the good one, and still 17x larger than the 141 KB JPEG. Lossless encoding of a photograph is a category error. Hold that thought, because it comes back as a real bug in a minute.
Building it: the Go side
Everything below is the real shape of Grit's internal/media package, stripped of the parts specific to the framework. Two dependencies, both pure Go, so your API stays a single static binary and you can keep cross-compiling to Linux from whatever laptop you have:
go get github.com/disintegration/imaginggo get github.com/HugoSmits86/nativewebp
Step 1: read the header before you decode anything
This is the step everybody skips, and it is a denial of service.
// DecodeConfig parses only the header, so this costs nothing, and it is the// only chance to refuse a decompression bomb: once Decode runs, the memory// is already committed.cfg, _, err := image.DecodeConfig(r)if err != nil {return Result{}, fmt.Errorf("reading image header: %w", err)}if px := int64(cfg.Width) * int64(cfg.Height); px > int64(maxPixels) {return Result{}, fmt.Errorf("image is %dx%d (%d megapixels), over the %d megapixel limit",cfg.Width, cfg.Height, px/1_000_000, maxPixels/1_000_000)}if _, err := r.Seek(0, io.SeekStart); err != nil {return Result{}, fmt.Errorf("rewinding after the header: %w", err)}
Why it matters, measured:
solid-colour PNG on the wire 929 KB 12000x12000 = 144 megapixels decodedrefused with a 50 MP limit: image is 12000x12000 (144 megapixels),over the 50 megapixel limit
A flat-colour PNG compresses to almost nothing whatever its dimensions. That 929 KB file decodes to 144 million pixels at 4 bytes each: 576 MB of heap, from a file under a megabyte. Ten of those arriving together is 5.7 GB and your process is gone.
Note what cannot save you here. Your upload size limit sees 929 KB and waves it through, because on the wire it is small. Your reverse proxy's client_max_body_size sees the same 929 KB. The only place this is catchable is between reading the header and committing the pixels, which is a window about four lines wide.
I use 50 megapixels as the limit: it passes a 48 MP professional camera frame and refuses the bomb.
Step 2: decode with orientation, which also strips EXIF for free
src, err := imaging.Decode(r, imaging.AutoOrientation(true))if err != nil {return Result{}, fmt.Errorf("decoding image: %w", err)}
AutoOrientation(true) is not optional. A photo taken in portrait on a phone does not contain portrait pixel data. It contains landscape pixels plus an EXIF rotation flag, and the viewer is expected to apply it. Decode without that option and every resize you do produces a sideways image, which will be reported to you as "the thumbnails are rotated" by a confused user about a week after launch.
The second effect is free and more important than it sounds. Because you are re-encoding from decoded pixels, no source metadata survives. A phone photo carries GPS coordinates. A marketplace where sellers upload product photos, without this step, publishes the seller's home address alongside every listing. I have seen that ship.
Step 3: resize, and never scale up
func resize(src image.Image, s Size) image.Image {if s.Width <= 0 && s.Height <= 0 {return src}if s.Crop && s.Width > 0 && s.Height > 0 {return imaging.Fill(src, s.Width, s.Height, imaging.Center, imaging.Lanczos)}b := src.Bounds()w, h := fitDimensions(b.Dx(), b.Dy(), s.Width, s.Height)if w == b.Dx() && h == b.Dy() {return src // already inside the box: do not touch it}return imaging.Resize(src, w, h, imaging.Lanczos)}
Three decisions in there, all of which I got wrong first.
Lanczos, not the default. Nearest-neighbour and bilinear are faster and visibly worse. Lanczos on a 12 MP image is a few hundred milliseconds, which you are spending on a file somebody just waited to upload. Spend it.
Fit never enlarges. If someone uploads a 200x150 image and your box is 1600, the answer is 200x150. Enlarging it spends bytes encoding pixels the source never had, and the result looks worse than the small original.
A zero side means unbounded, not zero. Fit(800, 0) should mean "800 wide, height whatever the aspect ratio says". Passed straight to imaging.Fit it produced an empty 0x0 image, which is a fun one to debug because the upload succeeds and the file is 70 bytes.
That last one bit me again while writing this post, in the script that produced the table above. My first version of the "quality only, no resize" row set the bounding box to zero to mean "do not resize", and reported 141 KB: identical to the full pipeline. I nearly published it, which would have had me claiming the quality slider does all the work. The box had been filled in with the default of 1600 behind my back, so I was measuring a resize and calling it a quality saving. The honest way to say "do not resize" is to pass a box bigger than any input, because Fit never enlarges.
Step 4: pick the format from the pixels, not from a config file
This is the design decision I am most confident about. The output format should not be something the developer configures. It is decidable from the image:
func resolveFormat(f Format, img image.Image) Format {if f != Auto {return f}if hasAlpha(img) {return WebP // lossless, keeps transparency, beats PNG on size and speed}return JPEG // ~20x smaller than any lossless encoding of a photograph}
Measured, on a transparent logo:
transparent logo, source PNG 41 KB 1200x1200 image/pngAuto (sees the alpha) 8 KB 1200x1200 image/webpforced JPEG (alpha destroyed) 33 KB 1200x1200 image/jpeg
Auto gives you 8 KB and keeps the transparency. Forcing JPEG gives you 33 KB, four times bigger, and the logo now has a black box behind it. That is the single most common image bug in hand-rolled pipelines: a config that says format: jpeg, and every transparent asset in the product silently grows a background.
With Auto as the default, that bug is unrepresentable. You cannot destroy transparency by forgetting a setting.
Now the trap inside the trap, which took me an embarrassingly long time:
// The threshold is not 0xffff, because alpha survives resampling as values a// hair under opaque. Treating those as transparency pushes every resized// photograph down the lossless path and makes it ~20x larger.func hasAlpha(img image.Image) bool {if op, ok := img.(interface{ Opaque() bool }); ok && op.Opaque() {return false}b := img.Bounds()for y := b.Min.Y; y < b.Max.Y; y++ {for x := b.Min.X; x < b.Max.X; x++ {if _, _, _, a := img.At(x, y).RGBA(); a < 0xff00 {return true}}}return false}
Resampling is arithmetic over neighbouring pixels, alpha included. A fully opaque photograph, after Lanczos, has pixels whose alpha is 65279 instead of 65535. Test for a < 0xffff and every resized photo reads as transparent, takes the lossless path, and comes out at 2471 KB instead of 141 KB. The symptom is that your pipeline appears to work and your storage bill does not go down, which is the worst kind of bug: no error, no crash, just a silent 17x.
Each rendition gets its own format decision, by the way, rather than inheriting the primary's. A square crop can easily cut away the transparent margin that made the full image a WebP.
Step 5: encode
func encode(img image.Image, f Format, quality float64) ([]byte, error) {var buf bytes.Bufferswitch f {case PNG:e := png.Encoder{CompressionLevel: png.BestCompression}if err := e.Encode(&buf, img); err != nil {return nil, fmt.Errorf("encoding png: %w", err)}case WebP:if err := nativewebp.Encode(&buf, img, &nativewebp.Options{}); err != nil {return nil, fmt.Errorf("encoding webp: %w", err)}default:if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: jpegQuality(quality)}); err != nil {return nil, fmt.Errorf("encoding jpeg: %w", err)}}return buf.Bytes(), nil}
On quality, since we established it is the small lever: 0.82. That is roughly where JPEG stops being distinguishable from the source on a photograph. Below about 0.75, artifacts start showing on gradients and skin, which is exactly where your users' faces are.
One honest limitation of the pure-Go stack: there is no pure-Go lossy WebP encoder, so nativewebp writes lossless VP8L. That is the right choice for transparency and the wrong choice for photographs, which is precisely why Auto sends photos to JPEG instead. More on the escape hatch at the end.
Step 6: bound the concurrency, or the pixel limit does not help
// One decode per CPU. A decoded 50 megapixel image is about 200 MB, and// uploads arriving together were each decoded at once.var transformSlots = make(chan struct{}, runtime.NumCPU())func Transform(r io.ReadSeeker, p Profile) (Result, error) {transformSlots <- struct{}{}defer func() { <-transformSlots }()// ...}
Your per-image pixel cap gives you a per-image memory bound. It gives you nothing at all about the server, because twenty concurrent uploads of perfectly legal 50 MP images is 4 GB. A buffered channel as a semaphore turns a per-request bound into a process bound, and it is three lines.
This is a different limit from your HTTP handler's concurrency. Requests can pile up cheaply. Decoded bitmaps cannot.
Step 7: optimise before storing, not after
This is the architecture mistake, and the one I most want to save you from, because the obvious design is wrong in a way that is hard to see.
The obvious design: accept the upload, store the original, enqueue a background job to make the renditions, return the response. It is textbook. Every tutorial does it. And it has a bug that cost Grit real money in storage before I caught it.
The response you return contains the file reference that the client writes into the record. At the moment you return it, the job has not run, so the thumbnail URL is empty. The row gets written with no thumbnail, and when the worker finishes a few hundred milliseconds later it writes a thumbnail that nothing on earth points at. Every thumbnail the system produced was orphaned: generated, stored, paid for monthly, referenced by nothing.
So the primary transform runs inline, in the request:
if media.IsOptimisable(mimeType) {res, err := media.Transform(file, profile)if err != nil {// A file nobody can decode is not necessarily a lost cause: the// profile decides whether to refuse it or keep it as it came.if profile.OnError == media.Reject {return fail(c, "That image could not be processed")}log.Printf("media: keeping %s unoptimised: %v", header.Filename, err)} else {key = storage.NewKey("uploads", res.Primary.Ext)// ... store the primary, then the renditions}}
Two consequences, both good. The row is only ever written with final URLs. And the 5 MB original never lands in your public prefix at all, which matters if anyone can guess a key.
The cost is the 659ms, on the request. I think that is the correct trade for a file the user is already watching a progress bar for. If you disagree, the fix is not to go back to the async version: it is to do the resize in the browser before the upload, which I come to below.
The renditions do go in parallel, because they are independent writes to object storage:
var wg sync.WaitGroupslots := make(chan struct{}, 4)for _, r := range res.Extra {wg.Add(1)slots <- struct{}{}go func() {defer func() { <-slots; wg.Done() }()if err := disk.Put(ctx, stem+"-"+r.Name+r.Ext, bytes.NewReader(r.Bytes), opts); err != nil {// A missing rendition is a smaller problem than a failed upload:// the primary is already stored and usable.log.Printf("media: rendition %q failed: %v", r.Name, err)return}// record it on the ref under a mutex}()}wg.Wait()
And one more thing about renditions, which is a one-word fix and a visible quality difference: derive every rendition from the source, not from the primary. Cropping a 400px thumbnail out of an already-downscaled 1600px copy throws away detail you still had in hand. It costs one extra resize and the thumbnails stop looking soft.
Step 8: keep the original, privately
if !profile.DiscardOriginal {file.Seek(0, io.SeekStart)origKey := "originals/" + stem + extdisk.Put(ctx, origKey, file, storage.PutOptions{ContentType: mimeType,Visibility: storage.VisibilityPrivate, // kept for reprocessing, not for serving})}
You will change your mind about the 1600px box, or AVIF will finally be worth adopting, and on that day the only thing that lets you regenerate is having kept the originals. Private, because a 5 MB file reachable by anyone who guesses a key defeats the whole exercise.
Note the field is named DiscardOriginal rather than KeepOriginal, and that is not a style preference. Profiles fill unset fields from defaults, and a bool cannot distinguish "unset" from "false". As KeepOriginal, every profile that did not explicitly mention it silently discarded the original while the documentation promised the opposite. Phrasing the field as the negative makes the zero value the recommended behaviour. This generalises: if your defaults layer over a struct, every bool must be named so that false is the answer you want.
Step 9: record what you produced
type FileRef struct {URL string `json:"url"`Key string `json:"key"`Width *int `json:"width,omitempty"`Height *int `json:"height,omitempty"`ThumbnailURL string `json:"thumbnail_url,omitempty"`// What the stored file actually is, after optimisation. Recorded rather// than inferred from the URL: asking for AVIF and silently receiving// JPEG is only safe if the ref says so.Format string `json:"format,omitempty"`// False when the transform failed and the original was stored as-is.Optimised bool `json:"optimised"`OriginalKey string `json:"original_key,omitempty"`Renditions map[string]Rendition `json:"renditions,omitempty"`}
Four of those fields exist because of specific pain:
WidthandHeightare what let the frontend reserve space and not shift the layout. Covered below.Format, because a pipeline that can fall back to a different encoder must not leave the client guessing.Optimised, because a pipeline that silently stores originals on failure needs some way to find them again. Without this flag the failures are invisible and permanent.Renditionsas a map, because deleting a file means deleting all of its objects. Every delete path in Grit originally worked fromKeyalone, so clearing an image field left its thumbnail and its original in the bucket forever, with nothing anywhere able to find them again. One upload is several objects. Model it that way from the first commit, because retrofitting it means writing a reconciliation job against a bucket you can no longer explain.
The Next.js side
The frontend work is smaller than people expect, because the server already did the hard part. But there are four things to get right.
Do not optimise twice
If your Go pipeline produced a 1600px JPEG, pointing next/image at it means Next fetches that file and re-encodes it on its own server, charging you a function invocation to turn a 141 KB file into a 138 KB file.
Two coherent positions, and you should pick one deliberately:
- Server-side renditions,
next/imageas a plain tag. You control the sizes, they are the same in every client including a mobile app, and there is no optimiser in the request path. Useunoptimized, or a plain<img>. next/imagedoes the work, and your Go pipeline only resizes down to a sane ceiling and strips metadata.
What you should not do is pay for both and think you are being thorough. I prefer (1), because an Expo app and a Go-rendered email cannot call /_next/image, and the point of renditions is that every client gets the same URL.
Allow the storage host, once
const storageURL = new URL(process.env.NEXT_PUBLIC_STORAGE_URL!)const nextImageHosts = [{protocol: storageURL.protocol.replace(':', '') as 'http' | 'https',hostname: storageURL.hostname,port: storageURL.port,pathname: '/**',},]export default {images: { remotePatterns: nextImageHosts },}
Derive it from the same environment variable the API uses, rather than hardcoding a hostname you will forget about on the day you move from MinIO to R2. And if you also set a Content-Security-Policy, its img-src needs the same origin: two lists, one source of truth, or you get a page where images load in development and are blocked in production.
One development-only gotcha that will cost you a morning: recent Next versions refuse to fetch images from hosts that resolve to a private IP, so your local MinIO on localhost:9000 starts returning errors that look exactly like a CORS problem. The fix is dangerouslyAllowLocalIP: isDev in the images config, scoped to development.
Use the width and height you stored
export function Photo({ file }: { file: FileRef }) {return (<Imagesrc={file.url}alt={file.name}width={file.width ?? 1600}height={file.height ?? 1200}sizes="(max-width: 768px) 100vw, 800px"/>)}
This is why step 9 records dimensions. Without them you either hardcode an aspect ratio and distort everything that does not match, or you let the image size itself on load and every page jumps as the photos arrive. The server already knew the dimensions at encode time, so passing them forward is free, and it is the difference between a page that settles and a page that visibly reflows.
Use the thumbnail in lists
<img src={file.thumbnail_url ?? file.url} alt="" width={80} height={80} loading="lazy" />
A table of fifty rows showing the 1600px primary in an 80px box downloads 7 MB to draw 4000 pixels. The whole reason to generate renditions is so a list can ask for the small one. Make sure your list components actually do, because file.url is right there and always works, which is how this one survives code review.
Or: do the resize in the browser
If you use presigned uploads, the file goes straight from the browser to storage and never touches your API, so the server cannot do any of the above. Then the resize has to happen client-side, which is a createImageBitmap plus a canvas toBlob, and it has a real advantage: a 3 MB upload becomes a 150 KB upload, so the transfer is 20x faster too, not just the storage.
The thing to get right is that the numbers must not be duplicated. Grit publishes its profiles as JSON:
GET /api/v1/media/profiles{"data": {"profiles": [{ "name": "default", "max_width": 1600, "max_height": 1600,"quality": 0.82, "format": "auto", "max_pixels": 50000000,"renditions": { "thumb": { "width": 400, "height": 400, "crop": true } } }],"backend": "pure-go","lossy_webp": false}}
A client that hardcodes 1600 and a server default of 1600 are the same number right up until somebody changes one of them. Publish the profile and fetch it.
When pure Go is not enough
Everything above has no cgo, which is why the API stays one static binary you can cross-compile from anywhere. When you outgrow it, the swap is a build tag over the same Transform signature, backed by libvips:
//go:build vips
What that buys, measured on that same 6.08 MB photograph in the same container:
pure Go (default) libvips (-tags vips)default profile 149.9 KB JPEG 1001ms 33.9 KB lossy WebP 1853msJPEG, forced 141.0 KB 950ms 123.7 KB 1366msAVIF downgrades to JPEG 79.9 KB 7544ms
The headline is the top-left against the top-right: 149.9 KB against 33.9 KB, because Auto on libvips resolves to lossy WebP instead of JPEG. That is a 4.4x improvement on an already-optimised file, and it is the single biggest remaining win available to you. It also streams, so a large image is never fully materialised in the heap, and it can write AVIF if your libvips was built with libheif.
Two rows in that table are worth reading twice.
Forcing JPEG throws the gain away. libvips at forced JPEG gives 123.7 KB, which does beat pure Go's 141.0 KB, but it is nearly four times the 33.9 KB that leaving the format on Auto would have given you. Having paid the cgo cost to get a lossy WebP encoder, pinning the format to JPEG is how you pay it and get nothing.
AVIF was not the win I expected. 79.9 KB against lossy WebP's 33.9 KB, so in this measurement it came out 2.4x larger, and took 7544ms against 1853ms to do it. I include it because the received wisdom is that AVIF is strictly smaller than WebP, and on this photograph at these settings it was not. Measure it on your own images before you reach for it, and particularly before you reach for it on a request somebody is waiting for.
What it costs: cgo. You are no longer cross-compiling from your laptop, libvips 8.10+ has to be present at build time and on the host at runtime, and your deploy story becomes a Docker build. That is a real cost, which is why it is the opt-in and not the default.
The part worth copying even if you never touch libvips: the speed difference is not mostly the encoder. It is that libvips resizes with Thumbnail, which uses a format's own reduced-resolution decoding to avoid ever materialising the full frame. If you need that on the pure-Go path, JPEG's DCT scaling is the same trick.
The short version
If you implement nothing else from this post:
- Resize. That is the optimisation. 93%, against the quality slider's 10%.
- Check
DecodeConfigbefore youDecode. Four lines between you and a 576 MB allocation from a 929 KB file. AutoOrientation(true), or portrait photos come out sideways and you publish your users' GPS coordinates.- Choose the format from the alpha channel, not from config, and use a threshold a hair below opaque, or every resized photo takes the lossless path and comes out 17x too big.
- Transform before you store, or your thumbnails are orphaned the moment they are written.
- One upload is several objects: the stored file, the renditions, the kept original. Model that on day one, because the delete path is where it bites.
- Bound the concurrency with a buffered channel, or the per-image limit bounds nothing.
The whole thing is about two hundred lines, and it is some of the highest-leverage code in most products, because images are usually the majority of both the bytes you store and the bytes your users download.
In Grit this is internal/media, already wired into the upload handler, running on every image field a generated resource produces. If you would rather not write the two hundred lines:
grit new myapp
And if you do write them yourself, the one I would most like to spare you is number 4. The transparency threshold is a one-character difference between a pipeline that works and a pipeline that quietly does nothing while your storage bill grows.
Founder of Grit and author of The Daily Grit. A 5-minute morning read on building full-stack apps with Go + React.
Build it with Grit
Go + React, batteries included. Scaffold a production-ready app in one command.
Get started