In the first article I wrote about zero values, error handling, and encryption. That was the painful but honest part: get it wrong and the tests go red immediately. This part is different. Everything here is something that ran “correctly” in Java for years without anyone understanding why, and that only revealed itself once I had to explain it again in a language with no magic in it.
Same family of services: user transactions. Six years old, Java 8 on Spring Boot 2.1, twenty-four endpoints, around three thousand four hundred requests per minute at peak. One PostgreSQL database, one Kafka cluster forwarding status changes to other teams, and one Redis for product cache and daily limits.
If the first service was about Java hiding null, this one is about Java hiding order. The order in which data is written, events are sent, caches are filled, and responses reach the client. In Java, the framework owned that order. In Go, I had to write it down, and writing it down forced me to look at everything that had merely been working by accident.
Transactions committed outside your code
This is what confused me most in my first two weeks, and I suspect it confuses anyone doing a similar port.
In the Java service, almost no endpoint mentions transactions. No begin, no commit, no rollback in any handler. There is one class in the filter package:
public class TransactionFilter extends OncePerRequestFilter {
private final PlatformTransactionManager txManager;
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
TransactionStatus status =
txManager.getTransaction(new DefaultTransactionDefinition());
try {
chain.doFilter(req, res);
txManager.commit(status);
} catch (Exception e) {
txManager.rollback(status);
throw e;
}
}
}
That is roughly the whole thing. One filter, registered once, and the entire application becomes transactional. Nobody complained for six years, because it is genuinely convenient: every request gets a transaction, every exception rolls back, and no developer ever has to think about boundaries.
When I moved to Go I went looking for the equivalent. There isn’t one. And after thinking it through, the absence is not a shortcoming of Go. That filter encoded four assumptions, and all four were wrong the moment the application grew.
Assumption one: the commit happens before the response is sent. It does not. chain.doFilter writes the response to the socket. If txManager.commit fails afterwards, the client already has a complete 200 OK while the database holds nothing. Our logs had twelve such cases in a year, and every one of them looked like an occasional “lost data” bug because no error ever reached the client.
Assumption two: everything inside the request joins that transaction. True, until someone opens a new one. A single @Transactional(propagation = Propagation.REQUIRES_NEW) anywhere breaks the chain. This service had three such methods, written years apart by different people, for reasons nobody remembered. The result: the audit log survived even when the user transaction it described was rolled back.
Assumption three: the transaction belongs to the request. It belongs to the thread. As soon as there is an @Async, a CompletableFuture, or a custom executor, the new thread carries no transaction at all. Three jobs in this service used @Async and actually ran outside any transaction, with no warning in the logs.
Assumption four, and the expensive one: anything sent to Kafka inside the request waits for the commit. It never did. kafkaTemplate.send publishes immediately and knows nothing about your database transaction. The real production order was: send the event, commit, and maybe roll back.
Consumers on the other side received TRANSACTION_COMPLETED for transactions that were never stored. They tried to read the row, found nothing, threw, and Kafka redelivered. Over and over. In the last month before the rewrite there were about one thousand nine hundred orphan events, and most of them were cycling through a retry topic into a dead letter queue nobody watched.
Redis was the same story. The cache was written before commit, with a thirty-minute TTL, so for thirty minutes everyone saw transactions whose status was never saved. That one was hardest to explain to operations, because the dashboard looked perfectly healthy: cache hits, fast responses, wrong data.
Why it is confusing in Go
In Go nothing is automatic. *sql.Tx is an ordinary value you have to carry into the functions that need it. That sounds like a burden, and at first it was. But once I wrote it, I realised the clarity was the point: the transaction boundary becomes something visible instead of something inherited.
My first port got it wrong, in the classic way for someone coming from Spring: every repository opened its own transaction.
func (r *TransactionRepo) Create(ctx context.Context, t Transaction) error {
tx, err := r.db.BeginTx(ctx, nil) // its own transaction
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, insertTransaction, t.ID, t.Status); err != nil {
return err
}
return tx.Commit()
}
This compiles, the tests are green, and in production it produces transactions with no audit row. One request touches four repositories, so there are four separate transactions each committing on its own. If the third fails, the first three are permanent.
The fix is one function holding the boundary, and repositories that accept a Querier instead of *sql.DB. I showed that pattern in the first article, but this time what matters is not the interface, it is the decision about what may live inside it.
func (u *Usecase) Submit(ctx context.Context, in SubmitInput) (*Transaction, error) {
var out *Transaction
err := u.db.WithTx(ctx, func(q Querier) error {
trx, err := u.transactions.Create(ctx, q, in)
if err != nil {
return fmt.Errorf("create transaction: %w", err)
}
if err := u.audit.Write(ctx, q, trx.ID, "SUBMITTED", in.Actor); err != nil {
return fmt.Errorf("write audit: %w", err)
}
// the event goes into the outbox inside the same transaction, not sent yet
if err := u.outbox.Enqueue(ctx, q, Event{
Topic: "transaction.submitted",
Key: trx.ID,
Payload: trx,
}); err != nil {
return fmt.Errorf("enqueue event: %w", err)
}
out = trx
return nil
})
if err != nil {
return nil, err
}
// the cache is only touched after the commit actually succeeded
if err := u.cache.Del(ctx, "transaction:"+out.ID); err != nil {
u.log.Warn("cache invalidate failed", "id", out.ID, "err", err)
}
return out, nil
}
Three things are now explicit. The response is not written until this function returns nil. Kafka is not called here at all. Redis is touched after commit, and if it fails that is a warning, not a reason to cancel a transaction that is already stored.
Outbox: one small table that ended the orphan events
Sending after commit creates a new problem: if the process dies between commit and send, the event is gone. So the event goes into a table first, inside the same transaction as the data. A publisher reads that table afterwards.
CREATE TABLE outbox (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
topic TEXT NOT NULL,
msg_key TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
sent_at TIMESTAMPTZ,
claimed_at TIMESTAMPTZ,
attempts SMALLINT NOT NULL DEFAULT 0
);
CREATE INDEX outbox_unsent_idx ON outbox (id) WHERE sent_at IS NULL;
This is one of the places where PostgreSQL genuinely helps, and I only realised how much friction I had been living with afterwards. FOR UPDATE SKIP LOCKED lets several workers take different rows without waiting on each other, and without any row being processed twice at the same moment. The claim fits in a single statement:
func (p *Publisher) Claim(ctx context.Context, limit int) ([]OutboxMessage, error) {
rows, err := p.db.QueryContext(ctx, `
UPDATE outbox
SET attempts = attempts + 1, claimed_at = now()
WHERE id IN (
SELECT id FROM outbox
WHERE sent_at IS NULL AND attempts < 10
ORDER BY id
LIMIT $1
FOR UPDATE SKIP LOCKED
)
RETURNING id, topic, msg_key, payload`, limit)
if err != nil {
return nil, fmt.Errorf("claim outbox: %w", err)
}
defer rows.Close()
var batch []OutboxMessage
for rows.Next() {
var m OutboxMessage
if err := rows.Scan(&m.ID, &m.Topic, &m.Key, &m.Payload); err != nil {
return nil, fmt.Errorf("scan outbox: %w", err)
}
batch = append(batch, m)
}
return batch, rows.Err()
}
The order is the whole trick: claim, commit, then publish. Rows are not locked during the network call to Kafka, so one slow broker does not hold up the other workers. If the process dies after the claim but before publishing, the row still has sent_at IS NULL and is picked up again next round. Which means an event can be delivered twice, and that is the contract I chose on purpose: at-least-once, not at-most-once.
So consumers have to be idempotent, and that is finally a good use for Redis.
func (c *Consumer) Handle(ctx context.Context, e Event) error {
key := "consumed:" + e.ID
ok, err := c.redis.SetNX(ctx, key, "1", 7*24*time.Hour).Result()
if err != nil {
return fmt.Errorf("dedupe check: %w", err)
}
if !ok {
return nil // already processed
}
if err := c.apply(ctx, e); err != nil {
if derr := c.redis.Del(ctx, key).Err(); derr != nil {
c.log.Error("dedupe key cleanup failed", "key", key, "err", derr)
}
return err
}
return nil
}
The key is deleted again when apply fails. Without that, one transient failure marks the event as done forever, and that is the kind of bug you meet three weeks later when a customer calls.
Twenty-one response shapes in one service
This section has nothing to do with Go, but it became far more painful during the rewrite, because every odd shape forced a decision: keep it or fix it.
Across twenty-four endpoints I found twenty-one different response shapes. Not twenty-one endpoints with twenty-one formats. Twenty-one variations, scattered, some differing by a single field.
A few I ran into:
// 1. One that wraps things neatly
return ResponseEntity.ok(new ApiResponse<>("S", "success", data));
// 2. One that returns the object directly
return transactionService.findById(id);
// 3. One that returns a List with no wrapper
return transactionService.listByUser(userId);
// 4. One that builds a Map by hand
Map<String, Object> res = new HashMap<>();
res.put("status", "OK");
res.put("result", data);
return res;
// 5. One that serializes to a String itself
return objectMapper.writeValueAsString(data);
// 6. One that returns 200 with an error message in the body
return ResponseEntity.ok(Collections.singletonMap("error", "not found"));
That last one caused most of the trouble. The mobile app reads the HTTP status, so 200 with {"error": "not found"} was treated as success, and the transaction detail screen rendered a blank page with no message. The mobile team patched it by scanning the body for the literal word "error", which broke again when another endpoint started returning an errors array.
There was also an endpoint that replied with HTML. Not on purpose: one @Controller (not @RestController) was left over from the Thymeleaf era, and its errors rendered as a white page with a stack trace if the dev profile was ever active. That reached production for four hours once.
And Spring’s own errors had their own format:
{
"timestamp": "2026-03-11T04:12:33.512+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/v1/transactions"
}
So clients had to understand three languages: the team’s handmade envelope, Spring’s default body, and HTML. When I counted, there were three different parsers on the web frontend and two in the mobile app. None of them was correct for every endpoint.
One envelope, one place that writes it
For the Go version I set one rule that could not be broken: a handler never writes to http.ResponseWriter directly. Everything goes through two functions.
type Envelope struct {
Data any `json:"data,omitempty"`
Error *APIError `json:"error,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
Fields map[string]string `json:"fields,omitempty"`
}
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(body); err != nil {
// the header is already sent, logging is all that is left
slog.Error("encode response", "err", err)
}
}
func writeError(w http.ResponseWriter, r *http.Request, err error) {
var apiErr *APIError
switch {
case errors.As(err, &apiErr):
writeJSON(w, statusFor(apiErr.Code), Envelope{Error: apiErr})
case errors.Is(err, ErrNotFound):
writeJSON(w, http.StatusNotFound, Envelope{Error: &APIError{
Code: "NOT_FOUND", Message: "transaction not found",
}})
case errors.Is(err, context.DeadlineExceeded):
writeJSON(w, http.StatusGatewayTimeout, Envelope{Error: &APIError{
Code: "TIMEOUT", Message: "request exceeded its deadline",
}})
default:
slog.ErrorContext(r.Context(), "unhandled error", "err", err, "path", r.URL.Path)
writeJSON(w, http.StatusInternalServerError, Envelope{Error: &APIError{
Code: "INTERNAL", Message: "internal server error",
}})
}
}
For lists, data holds the array and meta holds paging information. For validation errors, fields maps field names to messages, so a form can highlight the wrong input instead of guessing from prose.
What made this decision defensible was not the code, it was contract tests. I wrote twenty-four scenarios, one per endpoint, each with a fixed request and the response stored as a golden file. Any change to a response shape fails a test and has to be deliberate.
func TestContract(t *testing.T) {
for _, tc := range contractCases {
t.Run(tc.Name, func(t *testing.T) {
rec := httptest.NewRecorder()
tc.Handler.ServeHTTP(rec, tc.Request)
got := normalizeJSON(t, rec.Body.Bytes())
want := readGolden(t, "testdata/"+tc.Name+".json")
if diff := cmp.Diff(want, got); diff != "" {
t.Fatalf("response changed (-want +got):\n%s", diff)
}
})
}
}
I was tempted to preserve every old format so no client would break. That would have been the wrong call, and I am glad I did not make it. What I did instead: one new API version with a single envelope, the old version frozen and only accepting bug fixes, then switched off after every client migrated. It took four months, but there was not a single two-in-the-morning release because a JSON shape changed.
Thirty-four bugs nobody noticed for seven years
This is the part I least expected, and the part I talk about most when someone asks about rewrites.
I went in assuming the Java code was correct, because it had run for six years without a major incident. That assumption was wrong. What was true: the code ran, and most of its paths had never been exercised with data strange enough to prove they were right.
I did not find them by reading top to bottom. I wrote characterisation tests: run the Java service, record requests and responses, then run the Go version with the same input and compare. For what could not be recorded, I used thirty days of access logs, sanitised, about two point four million requests. The result: zero point three percent of requests produced different output. I traced those one by one and ended up with thirty-four logged bugs, eleven of them about flow rather than format.
A few I remember best:
Comparing Integer with ==. The old code compared status ids like this:
if (transaction.getStatusId() == STATUS_COMPLETED) { ... }
In Java, Integer is cached from -128 to 127. So while status ids stayed small, this reference comparison happened to be correct. The moment a new status arrived with id 130, it returned false even though the values were equal. Staging never used id 130. Production used it for corporate transactions, and the notification silently stopped being sent.
A switch with no break, and side effects running twice.
switch (status) {
case REJECTED:
auditLog.record("rejected", trx.getId());
// break forgotten
case COMPLETED:
notification.sendCompleted(trx);
break;
}
Rejected transactions still sent a “transaction completed” notification. Nobody noticed, because support assumed it was a mix-up from another system and closed the ticket as “cannot reproduce”.
The daily limit checked outside the transaction. The check-then-act pattern:
long used = limitRepository.usedToday(userId);
if (used + amount > dailyLimit) {
throw new LimitExceededException();
}
transactionRepository.create(trx, amount); // the commit happens far away in the filter
Two concurrent requests read the same number, both passed, and the daily limit was exceeded. No functional test could see this. A concurrency test with two hundred goroutines found it, and after recounting, two transactions had crossed the limit last month. The amounts were small, but on a product with larger limits that gap is not something you can shrug off.
No idempotency on the submit endpoint. The mobile app had a submit button that did not disable itself immediately. A double tap sent two requests, and both created different transactions. In the last three months there were thirty-one duplicate transactions, four of which had already settled and had to be reversed by phone.
A @Transactional that was never active. One important method called another on the same class:
public void process(Transaction trx) {
validate(trx);
persist(trx); // the @Transactional here never applies, self-invocation
}
Spring uses a proxy, so a call from inside the class never passes through it. For six years that persist method was not transactional. Nobody knew, because nobody ever checked.
A day boundary that shifted by one day. Date truncation used java.util.Date and the server’s timezone, while reports used LocalDate in Jakarta time. While the server ran in UTC, transactions between 00:00 and 07:00 WIB landed on the previous day. For years the daily report was always a little smaller than reality, and the gap was always written off as “transactions that failed at the gateway”.
Once the list was complete, I made a decision table. Not every bug was fixed, because some behaviours had become contracts with other systems.
| Bug | Decision | Reason |
|---|---|---|
Integer == on status id |
Fixed | Plainly wrong, nothing depended on it |
switch without break |
Fixed | Wrong notification, easy to prove |
Limit check-then-act |
Fixed + concurrency test | Caused daily limit breaches |
| Submit without idempotency | Fixed | Idempotency-Key added on the client |
| Counts including deleted rows | Fixed | Dashboard numbers moved, needed comms |
| Shifted date cut-off | Fixed, with backfill | Old rows needed a one-time correction |
| Kafka event ordering | Replaced with outbox | The old behaviour did not deserve preserving |
| Error 200 with an error body | Kept in API v1 | Old clients depended on it, removed with v1 |
That last row matters. There is one bug I knew about and deliberately kept for six months, because fixing it would have broken the old mobile app in users’ hands. Instead I documented it, tracked it as a metric, and removed it with API v1. An honest rewrite is not one that fixes everything at once.
Numbers
Measured before the full cutover, same load, with requests replayed from production logs:
| Metric | Java 8 | Go |
|---|---|---|
| p99 create transaction | 610 ms | 74 ms |
| Orphan Kafka events per month | 1,900 | 0 |
| Response format variations | 21 | 1 |
| Lines of code (no tests) | ~9,600 | ~6,100 |
| Endpoints | 24 | 24 |
Most of the p99 improvement came from removing the per-repository transactions and one N+1 query on the list endpoint, not from the Go runtime. Orphan events went to zero not because Go is smarter, but because events are now written in the same transaction and published after commit.
The endpoint count is deliberately unchanged. Adding or removing endpoints during a rewrite means clients change too, and that doubles the number of things that can go wrong.
What I would do differently
Record behaviour before touching code. The two-million-request replay was three days of work that saved weeks of debugging. Had I started by reading the code, I would have found five bugs, not thirty-four.
Do not let middleware own something you cannot see. One filter committing for every request feels efficient until a failure happens in the middle. The transaction boundary belongs in the layer that knows what is happening, not the layer that only knows a request went past.
Separate “kept” from “fixed” explicitly. Every time I found odd behaviour, I wrote it down: this is a bug, or this is a contract. Without that list, every conversation with another team ends in “it has always been like that”.
Treat the cache as something that is always allowed to fail. Redis being down must not fail a transaction. Every cache call in the Go version has a twenty-millisecond timeout and never returns an error to the caller. The result is a cache miss, and that is slow, not broken.
Treat Kafka as a separate system, not part of the request. Once an event leaves the process, it lives on its own. Outbox, idempotent consumers, and a monitored dead letter queue are not luxuries, they are the minimum for not losing data quietly.
Closing
Of the two services I rewrote, this is the one that changed how I read old code the most. Not because it had many bugs, but because the bugs were invisible. All of them were covered by something: transactions by a filter, responses by a framework, errors turned into a white page by Spring.
The Invisible Part Is the Expensive Part
If you are planning a similar rewrite, the single most useful piece of advice from this experience: before moving code, record its behaviour. Not documentation, not diagrams, but real requests and responses. That is where you find the things nobody ever wrote down, including the things that were wrong from the start. And on transactions, the rule I hold now: if I cannot point at the line that commits, I do not yet understand the service. In Java, that line was in a filter I had never opened. In Go, it is in a function I wrote, and I can read it from top to bottom. 🐹
Comments
comments powered by Disqus