I have recently been digging into understanding Golang concurrency, in particular the use of channels and worker pools. I wanted to compare performance between Go and Python (as many have done) because I have mostly read that Go outperforms Python with regard to concurrency. So I wrote two programs to scan an AWS account's S3 buckets and report back the total size. I performed this on an account that had more the 75 buckets totalling more than a few TB of data.

I was surprised to find that my Python implementation was nearly 2x faster than my Go implementation. This confuses me based on all the benchmarks and literature I have read. This leads me to believe that I did not implement my Go code correctly. While watching both programs run I noticed that the Go implementation only used up to 15% of my CPU while Python used >85%. Am I missing an important step with Go or am I missing something in my implementation? Thanks in advance!

Python Code:

Get the size of all objects in all buckets in S3
import os
import sys
import boto3

import concurrent.futures

def get_s3_bucket_sizes(aws_access_key_id, aws_secret_access_key, aws_session_token=None):

    s3client = boto3.client('s3')

    # Create the dictionary which will be indexed by the bucket's
    # name and has an S3Bucket object as its contents
    buckets = {}

    total_size = 0.0

    # Start gathering data...

    # Get all of the buckets in the account
    _buckets = s3client.list_buckets()

    cnt = 1
    with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
        future_bucket_to_scan = {executor.submit(get_bucket_objects, s3client, bucket): bucket for bucket in _buckets["Buckets"]}

        for future in concurrent.futures.as_completed(future_bucket_to_scan):
            bucket_object = future_bucket_to_scan[future]

                ret = future.result()
            except Exception as exc:
                print('ERROR: %s' % (str(exc)))
                total_size += ret


def get_bucket_objects(s3client, bucket):

    name = bucket["Name"]

    # Get all of the objects in the bucket
    lsbuckets = s3client.list_objects(Bucket=name)

    size = 0
    while True:
        if "Contents" not in lsbuckets.keys():

        for content in lsbuckets["Contents"]:            
            size += content["Size"]


    return size

# Main

if __name__=='__main__':
    get_s3_bucket_sizes(os.environ.get("AWS_ACCESS_KEY_ID"), os.environ.get("AWS_SECRET_ACCESS_KEY"))

Go Code:

package main

import (


type S3_Bucket_Response struct {
    bucket string
    count  int64
    size   int64
    err    error

type S3_Bucket_Request struct {
    bucket string
    region string

func get_bucket_objects_async(wg *sync.WaitGroup, requests chan S3_Bucket_Request, responses chan S3_Bucket_Response) {

    var size  int64
    var count int64

    for request := range requests {
        bucket := request.bucket
        region := request.region

        // Create a new response
        response := new(S3_Bucket_Response)
        response.bucket = bucket

        sess, err := session.NewSession(&aws.Config{
            Region: aws.String(region), 

        s3conn := s3.New(sess)

        resp, err := s3conn.ListObjectsV2(&s3.ListObjectsV2Input{
            Bucket: aws.String(bucket),

        if err != nil {
            if awsErr, ok := err.(awserr.Error); ok {

                switch awsErr.Code() {
                case "NoSuchBucket":
                    response.err = fmt.Errorf("Bucket: (%s) is NoSuchBucket.  Must be in process of deleting.", bucket)
                case "AccessDenied":
                    response.err = fmt.Errorf("Bucket: (%s) is AccessDenied.  You should really be running this with full Admin Privaleges", bucket)
            } else {
                response.err = fmt.Errorf("Listing Objects Unhandled Error: %s ", err)

            responses <- *response

        contents := resp.Contents
        size      = 0
        count     = 0

        for i:=0; i<len(contents); i++ {
            size  += *contents[i].Size
            count += 1

        response.size  = size
        response.count = count

        responses <- *response


func main() {

    var err  error
    var size int64
    var resp *s3.ListBucketsOutput
    var wg sync.WaitGroup

    sess, _ := session.NewSession()
    s3conn  := s3.New(sess)

    // Get account bucket listing
    if resp, err = s3conn.ListBuckets(&s3.ListBucketsInput{});err != nil {
        fmt.Println("Error listing buckets: %s", err)

    buckets := resp.Buckets
    size = 0

    // Create the buffered channels
    requests  := make(chan S3_Bucket_Request , len(buckets))
    responses := make(chan S3_Bucket_Response, len(buckets))

    for i := range buckets {

        bucket := *buckets[i].Name

        resp2, err := s3conn.GetBucketLocation(&s3.GetBucketLocationInput{                                                           
            Bucket: aws.String(bucket),                                                                                                       

        if err != nil {
            fmt.Printf("Could not get bucket location for bucket (%s): %s", bucket, err)

        go get_bucket_objects_async(&wg, requests, responses)

        region := "us-east-1"
        if resp2.LocationConstraint != nil {
            region = *resp2.LocationConstraint

        request := new(S3_Bucket_Request)
        request.bucket = bucket
        request.region = region

        requests <- *request        

    // Close requests channel and wait for responses

    cnt := 1
    // Process the results as they come in
    for response := range responses {

        fmt.Printf("Bucket: (%s) complete!  Buckets remaining: %d\n", response.bucket, len(buckets)-cnt)

        // Did the bucket request have errors?
        if response.err != nil {

        cnt  += 1
        size += response.size

  • \$\begingroup\$ A little of the Python formatting may have been messed up when I pressed the block quote button. Why it doesn't just add > to the beginning of each line is beyond me. -.- \$\endgroup\$ – Peilonrayz May 28 at 12:58
  • \$\begingroup\$ maybe you should not open a new session for each bucket. maybe you are being throttled because you perform too many concurrent connections. That golang consumes only 15% is expected as your code is not doing intensive work. This should be async wg.Wait(); close(responses); \$\endgroup\$ – mh-cbon Jun 3 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.