Rewriting a Java Service in Go: Nulls, Errors, and the Encryption That Kept Me Up

Table of Contents
Reading Progress
0%

The service was seven years old. Java 8, Spring Boot 2.1, a 480 MB Docker image, and a steady 1.4 GB resident set to serve roughly nine thousand requests per minute. From the outside it did one simple thing: store customer documents encrypted, and hand them back when asked. Inside there were six endpoints, a nightly re-encryption job, and about forty-one million ciphertext rows, none of which could be allowed to break.

I rewrote it in Go over nine weeks, with one other engineer.

I will not pretend it was smooth. For about two weeks I considered stopping, and the reason was not performance. The reason was encryption. But before I got anywhere near that, three other things were waiting: the way Java and Go treat empty values, the way they treat errors, and a design habit in the old code that turned out to be a time bomb.

Why I touched this service at all

The official reasons were boring. Dependencies could no longer be upgraded without changing code, CVEs had piled up in a third-party crypto library, and exactly one person understood the flow end to end. When that person took leave, we prayed.

The unofficial reason was also boring: cost. Nine thousand requests per minute do not need 1.4 GB of memory. What made it big was not the workload. It was the layer of connection pools, session caches, and an ORM that pulled every column on every query.

So the target was clear from day one: behaviour had to be identical, including the ciphertext format. Not “similar”. Identical. If a single byte shifted, forty-one million old rows would become garbage, and no backup would save us from the conversation with the audit team.

What I did not realise at the time: the hard part was not writing Go. The hard part was finding every implicit assumption that Java had been quietly covering for seven years.

Zero is not null, and the difference is expensive

This was the first surprise, and the one I still catch most often when reviewing ports.

In Java, a field on an object has two very different states: it holds a value, or it is null. That difference is often used to carry business meaning.

public class CustomerDocument {
    private Long id;
    private Integer issuedYear;   // null = year not recorded yet
    private Boolean verified;     // null = not reviewed yet
    private String nik;
}

In Go, every type has a zero value. int is 0, string is "", bool is false, and time.Time is 0001-01-01T00:00:00Z. A struct is never nil. So the naive port of a Java Integer is int32, and that is where things start to go wrong.

type CustomerDocument struct {
    ID         int64
    IssuedYear int32
    Verified   bool
    NIK        string
}

Three states become two. null and 0 are both 0. null and false are both false.

That looks trivial until it reaches production. In the old service, verified being null meant “awaiting review”. In our first port, false also meant “awaiting review”, so the happy path still worked. What broke was the daily report: a query filtering where verified = false, which used to catch only genuinely rejected documents, now caught two thousand three hundred documents that had not been processed at all. The dashboard number jumped, the operations team panicked, and I spent an afternoon explaining that no data had been lost.

The fix is not simply switching to pointers, although that is part of it.

type CustomerDocument struct {
    ID         int64
    IssuedYear *int32
    Verified   *bool     // nil = not reviewed, false = rejected
    NIK        string
}

Pointers give you the third state back. But once every field is a pointer, you are writing Java with Go syntax, plus a dereference on every line and a fresh nil-pointer risk. What I settled on: use a pointer only where “no value” genuinely means something different from “zero value”. A missing issue year? Pointer. A document count that is naturally 0 when empty? Plain int, do not force it.

Two other places where this bites, and which tutorials rarely mention.

First, the database. database/sql refuses to scan NULL into a non-pointer type:

var doc CustomerDocument
err := row.Scan(&doc.ID, &doc.IssuedYear, &doc.NIK)
// sql: Scan error on column index 1, name "issued_year":
// converting NULL to int32 is unsupported

The message is clear and it appears in tests, so this is the cheap kind of mistake. For nullable columns, pick *int32 or sql.NullInt32. I prefer pointers so the layer above never has to know about database-specific types.

Second, JSON. omitempty drops zero values, not just missing ones:

type Response struct {
    Verified *bool `json:"verified,omitempty"`
    Score    int   `json:"score,omitempty"` // score 0 disappears too
}

A score of zero is legitimate information. If the field vanishes, the client cannot tell “the score is zero” from “the field was not sent”. The lesson: do not let omitempty decide your API semantics. Say explicitly which fields may be absent and which must always be present, even when zero.

One more, very Go-specific: time.Time has no nil. If you want to test for an unset expiry date, if doc.ExpiredAt == nil will never compile. The correct check is doc.ExpiredAt.IsZero(), which is only safe if you are sure no valid record is dated January 1st of year 1. For a timestamp that may genuinely be empty, a *time.Time is more honest.

try/catch is gone, but the problem is not

In Java, failure is part of a function’s signature. If a method throws GeneralSecurityException, the compiler makes the caller aware. In Go, an error is a returned value, and the compiler does not care whether you checked it.

The old code looked roughly like this:

public Document read(String id, String payload) {
    try {
        byte[] plain = crypto.decrypt(payload);
        return mapper.readValue(plain, Document.class);
    } catch (GeneralSecurityException | IOException e) {
        throw new VaultException("cannot read document " + id, e);
    } finally {
        metrics.record("read", id);
    }
}

The Go equivalent looks simpler, but it quietly moves responsibility to you:

func (s *Service) Read(ctx context.Context, id string, payload []byte) (*Document, error) {
    plain, err := s.cipher.Decrypt(payload)
    if err != nil {
        return nil, fmt.Errorf("decrypt document %s: %w", id, err)
    }

    var doc Document
    if err := json.Unmarshal(plain, &doc); err != nil {
        return nil, fmt.Errorf("decode document %s: %w", id, err)
    }

    return &doc, nil
}

Three things I took away from this section.

First, %w is not decoration. Without it the error chain breaks and errors.Is stops working. With it, the message still reads well in logs, and callers can still ask what kind of failure this actually was. For this service we defined domain errors in one place:

var (
    ErrNotFound       = errors.New("document not found")
    ErrInvalidCipher  = errors.New("invalid ciphertext")
    ErrKeyUnavailable = errors.New("key unavailable")
)

Then mapped them to HTTP once, in the handler, instead of spraying that logic across layers:

func (h *Handler) writeError(w http.ResponseWriter, err error) {
    switch {
    case errors.Is(err, ErrNotFound):
        http.Error(w, "not found", http.StatusNotFound)
    case errors.Is(err, ErrInvalidCipher):
        http.Error(w, "payload could not be read", http.StatusUnprocessableEntity)
    case errors.Is(err, ErrKeyUnavailable):
        http.Error(w, "key service unavailable", http.StatusServiceUnavailable)
    default:
        h.log.Error("unhandled error", "err", err)
        http.Error(w, "internal error", http.StatusInternalServerError)
    }
}

Second, defer replaces finally, but not automatically. defer rows.Close() and defer tx.Rollback() are the Go answer to try-with-resources. The catch: a defer inside a loop does not run until the function returns, so if you process ten thousand rows in one function you are holding ten thousand result sets open. Wrap each iteration in a closure, or close explicitly.

Third, Go gives you no stack trace. In Java one printStackTrace points at the failing line. In Go you only get the message chain. That is plenty if every layer adds useful context, and completely useless if you write return err everywhere. Our rule: each layer adds context it alone knows, and does not repeat what is already there. The result reads like read document 8f3a: decrypt document 8f3a: invalid ciphertext: bad padding, which tells you where to look without a debugger.

As for panic: I only use it for conditions that cannot happen, like a required config value missing at startup. Never for something a user can trigger. If a panic shows up in production logs, that is a programmer bug, not an operational event.

Repositories inside repositories

This is the part that saved us the most time, and it had nothing to do with the language.

The Java code had one repository calling another:

@Repository
public class ApplicationRepository {

    @Autowired private JdbcTemplate jdbc;
    @Autowired private CustomerRepository customerRepository;
    @Autowired private DocumentRepository documentRepository;

    public List<ApplicationView> findAll() {
        return jdbc.query("select id, customer_id, status from applications", (rs, i) -> {
            Customer customer = customerRepository.findById(rs.getLong("customer_id"));
            List<Document> documents = documentRepository.findByCustomer(customer.getId());
            return new ApplicationView(rs.getLong("id"), customer, documents, rs.getString("status"));
        });
    }
}

At a glance nothing is wrong. It is an extremely common Spring shape: a repository uses another repository so callers do not need to know the details. Spring also makes it feel safe, because @Transactional on the outer method silently covers the inner queries too.

My first port kept that structure exactly, since the goal was to move behaviour, not redesign. The result: the list endpoint got slower than the Java version, even though Go is supposed to be faster here.

The cause took ten minutes to find once query logging was on. A single list request with two hundred applications ran one query for the applications, then two queries per row. Six hundred and one queries for one page. In Java that number was hidden by a large connection pool and a second-level cache. In Go, with an honest database/sql, it showed up directly in latency.

The more dangerous part was transactions. In Java, a nested repository joins the caller’s transaction automatically. In Go there is no magic propagation. If each repository grabs its own connection from the pool, those queries can run on different connections, outside the transaction, reading a different snapshot. No error, no warning. You just get data that is sometimes right and sometimes not.

The fix had two layers.

First, a repository may only touch its own aggregate. The application repository no longer calls the customer repository. Assembly moved up to the usecase layer, which is the layer whose job is coordination.

func (u *Usecase) ListApplications(ctx context.Context, limit int) ([]ApplicationView, error) {
    apps, err := u.apps.List(ctx, limit)
    if err != nil {
        return nil, fmt.Errorf("list applications: %w", err)
    }

    customerIDs := uniqueCustomerIDs(apps)
    customers, err := u.customers.FindByIDs(ctx, customerIDs)
    if err != nil {
        return nil, fmt.Errorf("load customers: %w", err)
    }

    return assemble(apps, customers), nil
}

Two queries instead of six hundred and one. FindByIDs builds a single IN with placeholders generated from the argument count, not from string concatenation.

Second, transactions became explicit and shareable. I defined the smallest useful interface and let repositories accept either implementation:

type Querier interface {
    QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
    QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
    ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

type Tx interface {
    Querier
    Commit() error
    Rollback() error
}

func (db *DB) WithTx(ctx context.Context, fn func(q Querier) error) error {
    tx, err := db.sql.BeginTx(ctx, nil)
    if err != nil {
        return err
    }
    if err := fn(tx); err != nil {
        _ = tx.Rollback()
        return err
    }
    return tx.Commit()
}

Now both *sql.DB and *sql.Tx satisfy Querier, so repository code never needs to know whether it is inside a transaction. The usecase decides the boundary, in one place, readable from top to bottom.

The side effect was almost funny: after the cleanup, p99 on the list endpoint dropped from 380 ms to 42 ms. Nearly all of it came from removing the nested repositories, not from changing languages. Had I only ported the Java code mechanically, the result could have been slower than the original, and I would have blamed Go.

Encryption: the part that nearly stopped me

Everything up to here could be done over a coffee. This part could not.

The legacy ciphertext format had to be read exactly as it was. Not because it was good, but because forty-one million rows were already written in it. Here is its precise shape:

  • AES-128-CBC with PKCS5Padding.
  • A random 16-byte IV prepended to the ciphertext.
  • The whole payload Base64-encoded.
  • The key derived from a passphrase with PBKDF2WithHmacSHA1, ten thousand iterations, and an 8-byte salt written directly in the source.

In Java it all looks tidy:

private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

public String encrypt(String plaintext, SecretKey key) throws GeneralSecurityException {
    byte[] iv = new byte[16];
    secureRandom.nextBytes(iv);

    Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
    byte[] body = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));

    byte[] payload = ByteBuffer.allocate(iv.length + body.length)
        .put(iv).put(body).array();

    return Base64.getMimeEncoder().encodeToString(payload);
}

In Go I rewrote this and spent three days just getting 512 production ciphertext samples to decrypt to identical output. Not similar. Identical, down to the last character, because that plaintext feeds a document checksum.

Four traps, none of them obvious from the documentation.

MIME Base64 is not plain Base64. Base64.getMimeEncoder() inserts a line break every 76 characters and ends with \r\n. Go’s base64.StdEncoding.DecodeString rejects that with illegal base64 data at input byte 76. That cost me the first two hours: I was convinced the key was wrong when the only problem was a line break.

func normalizeBase64(s string) string {
    return strings.Map(func(r rune) rune {
        switch r {
        case '\r', '\n', ' ', '\t':
            return -1
        }
        return r
    }, s)
}

PKCS5 is not PKCS7, except Java pretends it is. In JCE, "AES/CBC/PKCS5Padding" actually applies PKCS7 padding for a 16-byte block. If you write a strict PKCS5 unpad (8-byte block) from the specification, it fails on certain lengths, and only sometimes. That is my least favourite class of bug: it appears on one document in seven and never on your machine.

func pkcs7Unpad(b []byte, blockSize int) ([]byte, error) {
    if len(b) == 0 || len(b)%blockSize != 0 {
        return nil, ErrInvalidCipher
    }
    n := int(b[len(b)-1])
    if n == 0 || n > blockSize || n > len(b) {
        return nil, ErrInvalidCipher
    }
    for _, v := range b[len(b)-n:] {
        if int(v) != n {
            return nil, ErrInvalidCipher
        }
    }
    return b[:len(b)-n], nil
}

Platform charset. One old job on a Windows box called getBytes() with no argument, which uses the machine’s default charset. For years the output was fine because every character that passed through was ASCII. The moment a name with a diacritic appeared, the ciphertext differed and the checksum stopped matching. In Go, []byte(s) is always UTF-8, so new code is safer by default, but old data still has to be read with the right assumption.

Data that did not follow its own format. Of the 512 samples, nine rows from 2019 used a static IV instead of a prepended random one. No documentation, no comment, probably an older job before the current one. For those nine rows I added a dedicated fallback path, logging every time it is used so we can migrate them once and delete the branch.

After all of that passed, I found something bigger than any of those bugs: the old format had no authentication. AES-CBC without a MAC is malleable, and differing error messages for “bad padding” versus “bad JSON” leak information. That cannot be fixed without changing the data, so the answer was not a patch. The answer was a migration.

All new writes use AES-256-GCM with a version prefix:

func (c *Cipher) Encrypt(plain []byte) (string, error) {
    block, err := aes.NewCipher(c.key256)
    if err != nil {
        return "", fmt.Errorf("new cipher: %w", err)
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return "", fmt.Errorf("new gcm: %w", err)
    }

    nonce := make([]byte, gcm.NonceSize())
    if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
        return "", fmt.Errorf("read nonce: %w", err)
    }

    sealed := gcm.Seal(nonce, nonce, plain, c.aad(id))
    return "v2:" + base64.RawURLEncoding.EncodeToString(sealed), nil
}

The read path supports both formats, chosen by prefix rather than guesswork:

func (c *Cipher) Decrypt(id, encoded string) ([]byte, error) {
    if strings.HasPrefix(encoded, "v2:") {
        return c.decryptGCM(id, strings.TrimPrefix(encoded, "v2:"))
    }
    return c.decryptLegacyCBC(encoded)
}

The nightly job then became: read an old row, decrypt with the CBC path, re-encrypt with GCM, save, record the cursor. Batches of five hundred, idempotent, safe to restart from the beginning.

A job that used to take four hours and twenty minutes finished in twenty-six. Not because Go is magic, but because the Java version opened a new database connection for every single row.

Numbers once it was all running

I do not want to end this with “Go is much faster”. These are measurements taken before the full cutover, under the same load:

Metric Java 8 Go
Docker image size 480 MB 17 MB
Steady-state RSS 1.4 GB 70 MB
p99 document read 380 ms 42 ms
Nightly re-encryption job 4 h 20 m 26 m
Lines of code (no tests) ~14,000 ~9,200

The honest caveat: most of the p99 improvement came from removing nested repositories and the ORM, not from the Go runtime. Memory dropped because there is no JVM and no session cache, which is genuinely the runtime. Image size dropped because it is one static binary, also the runtime.

Line count dropped not because Go is terser, but because we deleted three layers of abstraction that nobody was using.

What I would do differently

Golden fixtures first, before a single line of production code. I only built the 512-sample suite in week three, then spent the next three days on what should have been the first test. If you are moving a service that touches encrypted data, collect real ciphertext, the expected plaintext, and turn them into tests. Cheapest safety net I have ever built.

Port behaviour first, design later, and never both at once. We were fixing repository structure while moving code. When a test failed, we could not tell whether it was a porting bug or a design change. Splitting it into two phases made everything calmer.

Do not rewrite what does not hurt. One reporting endpoint is still Java today, behind the same reverse proxy. Nobody complains, and nobody has to rush it. A total rewrite looks great in an architecture document, but what the business needs is a service that stays alive during the process.

Ship observability before cutover, not after. Structured logs, per-endpoint metrics, and traces carrying the document ID. When one row failed to decrypt at two in the morning, I found it in two minutes because the ID was on every layer.

Treat if err != nil as documentation. Every error branch you write is a chance to explain what can fail and what that means for the caller. If you only write return err, you throw that chance away.

Closing

I do not regret moving to Go. Deploys take seconds now, memory makes sense, and a single binary with no JVM makes on-call a little calmer. But if someone asks whether Go solved our problem, the honest answer is: half of it. The other half was solved by dismantling a design that had been wrong since it was written in Java.

The Language Changed, the Habits Got Fixed

blog-img

If you are planning a similar rewrite, the order is roughly this: freeze the behaviour that must not change, especially anything touching stored data. Then move the code. Then clean up the structure. And put encryption last on the list of things to do, because it is the part that forgives the fewest small mistakes. One thing I brought home from those nine weeks: the biggest difference between Java and Go is not syntax, it is how much each one does quietly. Java hides `null` behind exceptions, hides transaction boundaries behind annotations, and hides queries behind an ORM. Go hides nothing. At first that is exhausting. A few weeks later I found it calming, because everything that can fail is visible in front of you. 🐹

Comments

comments powered by Disqus