Go lang

It has been a crazy few months in startup land. The interesting thing for me about startups is no matter how crazy it is compared to corporate work, I find myself really content amidst the chaos. The big change here is we have decided to build our backend architecture in Go instead of Java. Having done Java for 19 years this is a big change, but for business decisions we decided that the trade offs with Go were better for our long term business needs than the trade offs with Java. Now that I have been using it for a few months I figured I would discuss some of the differences between the languages and what I like and dislike about each.

First Impressions

Just from an initial impression to me, Go seems like a cleaned up C language. You basically have a low level language with primitives and structs, slices (lists in Java), maps, and not a lot more. You end up having to build and write more code than in Java. But in sort of a nod to the good parts of OO they have interfaces and methods that you can attach to structs. At that point it is almost like a super lightweight C++.

I find that I spend a lot more time wiring up code in Go. Having done Spring now for 10 years you spend very little timing wiring up your code as everything is autowired, and you mostly just focus on business logic. Same for SQL Spring Data provides such a nice DSL you don’t write that many database queries either. In my initial analysis it took about 10 times as much code to write a simple REST backend in Go as compared to Spring Boot. But it used 1/10 as much RAM or less. This is the reason we decided to spend more money on Development costs (as it is much more code to write than Java) as we believe the savings on cloud hosting costs down the line will make it a better decision for us.

Go produces a single binary just like Spring Boot gives you a fat jar so I consider them equal here, but the startup time for Go seems to be instant, where as due to all the reflection and wiring at startup in Spring it seems like those apps typically take about 5 seconds to start in my experience (if there is a database involved).

Ceremony

General

Go has taken some steps to remove the ceremony in the language. One of the big differences that I notice is that you no longer needs ()around your statements in for loops, while loops and if statements. I repeatedly find myself putting those in by default and then having the IDE remove them. Another big difference is you no longer have to terminate your statements with ;as the compiler automatically puts those in for you. A little bit like Groovy in that regard.

Iteration

You would think that after doing all that work to remove ceremony that the language would be clean in general. But here is where I see the low level C type stuff come through. In Java if I want to iterate through a list it looks like this:

for (item : list) {

Basically it reads as for each item in the list, and the you operate on it. Go has a range statement to iterate through an array or slice. Here in lies a big difference in Go between Java is that you can return multiple values from a function or method. The designers of the language decided to have the range statement return both the index and the value. Generally in Java if I am using a for each it is because I don’t care about the index, I use a standard for loop if I need the index. Go has the standard for loop but for some reason they decided to return the index as well. You end up having to throw it away if you don’t care about it which feels like more ceremony again so the above statement ends up reading:

for _, item := range list { It is hard to look at that and think that reads better than the Java even though they got rid of the parenthesis.

But even this sort of misses the point as I am not even using for each that much in Java these days instead we have moved to a higher level yet and now use stream operations and handle everything in a functional style. What ends up happening in Java is you spend your time telling the language what you want to happen and let it sort the details of how to do it (lazy execution, or parallel execution, it doesn’t really matter with streams). In Go you spend your time telling the language how you want it to do the iteration so it feels like you are back down in the weeds again.

Initialization

Initializing an empty list also feels like it is more ceremony in Go. In Java you might have:

var list = new ArrayList<String>();

You look at that line and you have the ceremonly of the generics and the () to state which constructor you are calling and then the semicolon to terminate the statement. In go you end up with something like

list := []string{} again I wouldn’t call that better, just different. The ceremony here is the := which allows you to leave out the var at the front and you have the braces at the end which are initializing the struct. It is shorter but again neither seems to read better nor worse, just different.

References

One other big difference which really brings me back to C is you have to specify whether you are dealing with a value type or reference type in Go. In Java all primitives are value types and all Objects are reference types so you don’t have to spend any time thinking about it especially in a world of autoboxing. The drawback to the Java approach is if you need performance and memory compactness sometimes you need to use arrays of primitives and not collections. This is something that can definitely trip up a new programmer. Another problem is if autoboxing isn’t handled correctly it is possible for a NullPointerException to be thrown which could also be confusing to a junior developer.

In Go you have to explicitly thing about whether you are passing a value to a struct or a reference to it. Arrays and slices and maps are automatically reference types but any of your structs you have to explicitly declare if it is a pointer or a value type. For example

type struct Person {
  Name string,
  Age uint
}

pointerToPerson := &Person{Name:"Jeff", Age:41}

valueTypePerson := Person{Name:"The Doctor", Age: 904}

If you want to use pointerToPerson above you have to dereference it with the *. If the pointer is nil you will panic if you dereference it. On the other hand the value type if you don’t initialize it goes to default values so the default for the string is an empty string ""and the default for the integer would be 0.

Concurrency

Concurrency is where Go both shines against Java and feels lacking at the same time. Let’s talk about what is great if you want to call a function concurrently it is amazing you simply do:

go handleData() and handleData() will be executed concurrently. The great thing about go calls is they are extremely lightweight. When I read about project loom where they want to bring fibers and continuations to Java. Because they are much lighter weight than a thread in Java you can have thousands of them without a performance issue. It is my understanding that their is a threadpool underneath that executes your different go routines I think similar to an executor in Java with runables, but again I think the go routines are using much less memory than a Java Runnable.

This kind of light weight concurrency seems to be the direction everything is going whether it is the node system of events and async callbacks or even the reactive movement going through spring. Everyone is trying to execute more things concurrently with a very small thread pool.

There is much more ceremony in a Java Runnable or Callable. First I have to implement an interface and then put my code in a specific method. Then I need a Thread or an Executor on which to execute the code. If it were a Runnable and I needed a return type I would need to pass in some sort of concurrent collection to safely send the data back to the other thread in, or I could return it directly in the callable when I get a future out of that callable that can give me the return value.

Java definitely has a ways to go to catch up to go with the ease of concurrency, but the types are much richer for concurrency in Java so with java.util.concurrent.* one has access to about anything you need. In Go you pretty much just have channels to safely pass data between separate Go routines this again has that simple feeling of C where you are building everything up from primitives vs Java where the libraries are much richer.

Tooling

Here in you can tell how young of a language Go is. To me the tools feel like going back in time to around 2005 in Java. The debugger (delve) is primitive and I often find it not stopping at my break points or not showing me the values of all of my variables. I remember using JBuilder and Visual Cafe and some of the early Java IDEs and having similar issues of the debugger just not working that well. I find myself using printf statements to debug again which feels like going back in time 20 years.

IDE support seems decent though otherwise (if you throw out the debugging issues). I am using IntelliJ Ultimate with their Goland plugin and find myself very productive in writing code. It is the same IDE that I know and love from my Java work, and the understanding of the syntax in general seems to be great. I hear that VSCode is also pretty good for writing Go.

Enterprise Features

This is a small point but one that I just hit in the last week or so and that is that the language lacks support for batching SQL statements. Given that Java is such a strong enterprise language I just assumed that would be built into Go as well, especially given that the language is 9 years old, but maybe most of the internet type software being built isn’t using batch operations to slam a lot of data into a database at once.

Conclusion

At this point I still think Java is a more enjoyable language to program in. I like the higher level you can operate at with things like the stream api, and I like how opinionated Spring is. I think that saves you time setting up a new service and leads to consistency when dealing with new code that you haven’t seen before. Go concurrency model feels like it could be more powerful which is why there is that Java project loom to bring fibers and continuations to the language. The value types are an advantage and result in Go using very little memory compared to a typical spring project, which is again why in the Java world they are working on bringing value types into the language. Go is definitely powerful and fast and effective at what it does. If I were still a C programmer I would probably love it, as it feels like C without all the annoyances. As it stands now I can use it, and it works well, but I am not yet passionate about the language.

Serverless and Spring Cloud Function

We have been discussing going to a more serverless architecture at work and so I decided that I should do some research to see where that stuff is now. When I was at Choose we used AWS Lambda to implement the backend of an abandoned shopping cart service. We would then use that data to drive an email campaign to encourage the users to come back and finish purchasing an energy plan. It had a huge effect in driving conversion rates and we were able to implement the service in about 25 lines of vanilla java code. I opted not to use Spring as I judged the startup times to be too slow for it to be worth it. To manage libraries we used the maven shade plugin in our build process to build a fat jar.

In my current role we will deploy on AWS lambda as well. One thing I am looking for in considering serverless frameworks is what allows the developer to have a very nice flow as well, as back when we did the abandoned cart service debugging was a painful experience. At that point I think we did a bunch of console logging messages to figure it out. That won’t scale up for a development team that is going heavy into serverless it is too inefficient.

Then last week I came across this Spring Tips video about a new project Project Riff. I am happy to see Pivotal getting into this space as they build great frameworks and tools. And Riff seems no different it allows a developer to easily install it on their laptop and seems like it has first class support for Google Cloud and anyone’s infrastructure that is already running Kubernetes.

So I really liked the Riff part of that video. But then I was watching the Spring Cloud Function part. Now everyone who knows me knows that I love the Spring framework. I have been using it since 2008, and I think in terms of what it can do for you on Java server apps there is nothing else close. It really accelerates developer productivity and lets them focus on solving business problems. But as I watched this video I was sort of like I don’t get it. Like year I get that people want to use Spring in serverless, but when you watch it take 5 seconds to stand up a function, to me that is a deal breaker. It is too slow and if you are being charged by the second for your service paying 5 seconds to execute a function that will take less than a second is too expensive.

I was pretty much ready to write Spring Cloud Function off as a bad idea based on that then I saw something on Twitter about Dave Syer demoing something at Spring IO this week which brings massively faster startup times. I suspect it has something to do with the spring-context-indexer that Juergen talks about in this video, but I have been unable to find any examples or documentation on how to use it.

The other thing I need to take a look at is the AWS SAM Local tool. The big pain point I had doing Lamda’s a couple of years ago was around debugging them. This looks like it may solve that problem for us by giving us an convenient way to hook this into our development lifecycle.

Spring Boot 2.0

Spring Boot 2.0 has finally arrived. Unfortunately we aren’t yet in a position at the office to be able to begin the upgrade so I decided to start playing around with it on one of my projects at home as I didn’t want to wait until we were ready to update our app.

The first thing I noticed about it they removed findOne() from CrudRepository. This to me is a bad change for all the users of the framework. It is one of the most commonly used methods in Spring Data, and not people either have to refactor their code to use findById() which returns an Optional<> of the type and deal with the optional instead of a null or you have to add a findOne with an @Query to all of your repositories. I have worked on projects in the past that have hundreds of tables and Repositories. This change is forcing them to update hundreds of classes just to upgrade to Spring Boot 2.0. It seems to me a better choice would have been to @Deprecated on findOne and encourage people to upgrade to the new findById method.

The next breaking change I found was also in Spring Data. They removed the delete() method from CrudRepository that takes an ID as the type. It has been replaced by a deleteById() call. There is no good reason for this change. In Java we have method overloading so the language can determine whether to invoke delete() with the Entity or delete() with an ID. It seems like they were trying to be consistent with findById() but they just end up breaking a bunch of code in the process. The only benefit that I can see with this change is groovy will get happier as it seems to be very poor at understand overloaded methods.

The next change I noticed was when calling new PageRequest(page, size) it was telling me that constructor was deprecated. To me this is the right way to handle the situation. I clicked into the method and it suggested to use PageRequest.of() instead. That was an easy fix that I made and seems more consistent with Effective Java about using static factory methods instead of constructors.

Finally I got all my unit tests updated to replace the findOne calls with the findById changes I had made and I went to launch the application and Hibernate fell over. It looks like the new version of Hibernate requires me to specify a GenerationType of Identity with MySQL where before it didn’t force me to specify it.

All in all it wasn’t too bad to upgrade my toy application. I am really looking forward to using Spring Boot 2.0 going forward, but a little disappointed by some of the Spring Data breaking changes. I feel like this could have been transitioned in to make it easier to upgrade existing Spring Boot 1.5.x applications. It is interesting that 2.0 is the first release to support running under Java 9, and it is finally released a month before Java 9 goes away and Java 10 is released. Up next for my test application will be switching it to Java 9 to see if I see any issues with that.

MacOS Sierra Slowdown update

I have an update on my slowdown issues on Sierra. It appears the real problem lies in the AWS Java SDK. After talking to the spring boot people via github they were able to narrow it down to an Amazon issue. I opened an issue on github with Amazon and they responded that the version of the SDK that ships in the current spring cloud has this issue in it, and it has been fixed in a newer version of the SDK. One of the big value propositions of Spring Boot to me and the release train concept of Spring Cloud or Spring Data is that it is a collection of dependencies that have all been tested together, which lowers my risk of using them together. So I opened a request with Spring Cloud AWS to upgrade their SDK. Unfortunately they don’t seem very timely in responding to issues as I notice it looks like there are no responses on any of the issues raised in the last 2 weeks.

In the meantime I have a work around that doesn’t involve having to manually bump up your AWS SDK version and that is to set the following property in your application.properties file of your Spring Boot App:

cloud.aws.credentials.instanceProfile=false

Obviously setting this flag for your app running on AWS that uses the IAM profiles isn’t good, but it is a good local workaround on your development machine until the SDK gets updated in Spring Cloud.

A Two Month Recap

It has been a crazy couple of months. Since I last posted I made a trip out to San Francisco to meet the rest of the team I work with (and had a great time). If you live in Texas there is no better time to visit San Francisco then at the end of July. It was a welcome break from the heat. I had a great time and realized when I was out there that I hadn’t been out there since 2005, so I was over due for a trip. I had forgotten how much I love that city it is a really fun place to hang out (though not a place I would really want to live).

We are also about to launch our second Spring Boot Microservice. This one I am really excited about it is even more ambitious than our first one and should provide huge value to the business. The interesting new technology we used in this one is Amazon’s SQS (Simple Queue Service). I am going to say off the bat that the documentation for Spring Cloud is kind of crap, so I spent a lot of time debugging the framework to figure out how to integrate this thing. But now that we have it working it seems to work great. It definitely is pretty light on features compared to something like RabbitMQ, but it seems to get the job done and the Spring Integration is great. I am hoping to put out a blog post on how to configure it as we got hung up a few places with it.

One of the nice things about going to SQS is it forced me to upgrade our Monolith to Spring 4.2 from 4.0 as the current Spring Cloud Brixton release train won’t run on Spring 4.0. I am hoping to roll out Java 8 there as well in the next couple of weeks so that we will be sitting on a fairly current framework on our oldest app and our Microservices running the latest and greatest of everything.

We already have 2 more microservices planned out, it is just a matter of figuring out how they will fit into the product roadmap. I think once we get that delivered we will have cut our monolith down quite a bit and I hope at that point it will be small enough for me to convert it over to boot and simplify it. As I see lot of opportunities to really get everything we are doing lean which should let us turn around features for the business even faster.

Anyway that is the latest update, hopefully I can carve out some time to work on a SQS configuration post. Until next time…

We are live and MySQL settings

We’ll do it live..

The big news is our new Spring Boot micro service went into production! It has been running in production for just over a week and we have had 0 issues with it, everything just works! It ended up being two crazy sprints to get it done, but we shipped it this week with no production issues after it went live. My first big project at the new company couldn’t have gone any better. The team really pulled together to get it done which makes it even more rewarding.

MySQL Database Connections…

We did have one near miss though. It turns out that MySQL drops database connections that have been idle for 8 hours. We discovered that the morning we were about to go live. I really think this should be more widely publicized. It seems like the sensible opinionated default of Spring Boot should be to have the connection pool test the connections so that people don’t end up in this state. Anyway luckily additional testing the morning of uncovered this and I was able to find out how to fix it with some digging around. Just so I remember for the future the magic settings are:

The settings…

spring.datasource.remove-abandoned=true
spring.datasource.remove-abandoned-timeout=600
spring.datasource.testOnBorrow=true
spring.datasource.testWhileIdle=true
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.validationQuery=SELECT 1

What it all means…

So breaking it down, testOnBorrow checks the connection before the connection pool gives it to you. This is my first fix that I started with as it it has the connection pool test the connection with the validation query prior to returning it back to the application. This is good enough to fix the issue, but if all connections are killed like if the database had gone down and came back up it is a little slow the first time the app goes for a connection as it has to run through everything in the pool before it allocates a new connection for you.

The second thing I found was the test while idle and the time between eviction runs. With that every minute we test idle connections. This is great for 2 reasons, it keeps the connections alive with MySQL and if someone gets messed up with one of the connections we can be proactive about cleaning it up.

The third set of options I discovered in all this is the remove-abandoned option. This protects you from leaking connections in the application. Above it basically says if we haven’t returned a connection within 600 seconds consider that connection to be abandoned and remove it from the pool. I think with all of these options you are going to make your application much more resilient to database connection issues.

Gotta love open source and github

The Problem

I have been working on this project to make our app run in any Java Container. Currently we run in JBoss, but ideally I would like the app to work in JBoss or Tomcat, or TomEE or Wildfly. One of the challenges in making this change is to remove JBoss specific dependencies from our app and pull those libs into the webapp as part of our project. We did the first piece of this a couple of years ago when we stopped using JBoss’ version of Hibernate and pulled a newer version into our app. We have since upgraded JBoss versions so this is somewhat moot since the bundled version and our version are the same, but it is one less thing that I will have to deal with as part of this project.

The first part that I have decided to tackle is not using JBoss’ built in transaction manager and instead bundling one. Looking around it seems like my choices are Atomikos, Bitronix, or JBossTM in standalone mode. Our situation is somewhat more complicated based on the fact that we are not running an XA jdbc driver. Originally the company was using one, but at some point ripped it out because Microsoft SQLServer wouldn’t work correctly or scale with it in there. We are aware of the limitations of not running in XA mode.

Bitronix

That alone rules out Bitronix as they pretty much require XA to do their thing. I had also sort of ruled them out given that the commercial company behind them ceased operating some time ago, and ideally we want to be in a position to pay a company for support. I will say one nice thing about Bitronix is it does have good Spring Boot support.

Atomikos

Atomikos does have a paid supported version if we found we needed it down the line and they have support for a Non XA datasource. Another thing Atomikos has going for it, is that we are already using it for our persistence unit tests, though not with the NonXADataSourceBean but rather with Apache Commons DBCP. I switched over to the NonXADataSourceBean version and most of the unit tests seemed to work which was promising.

JBossTM aka Narayana

At the end of the day though my thinking was the lowest risk solution would be to use JBossTM in standalone mode. Given that we are already using JBoss’ built in version of it this seems to be the least amount of change we can do. The first challenge is actually finding anything out about the project. Just searching JbossTM or JBoss Transactions doesn’t find much for you. I eventually discovered it is called Narayana. Ignore the horribly designed website, I just found that tonight, I originally found it on the JBoss home pages and on github. JBoss has a quickstarts example github repository showing you how to use their stuff as well. The Spring example was sort of what I wanted, but not exactly so I figured why not just do a quick Spring Boot app as a proof of concept. So I forked the repository and added a Spring Boot app. I hit a problem though, I created a unit test to try out reverts my insert wasn’t reverting on a Runtime exception. Just to make sure I wasn’t completely crazy I created a quick Spring Boot app doing the same thing using Atomikos. That test app worked perfectly.

At this point I feared I would be forced into switching to Atomikos as that was all that I could prove was working with a trivial test. I went over to the JBoss forums as a last ditch effort and posted a question about it. Back in the day when I would post things to forums I would often get very little response or things would be vague cause it is hard sometimes on the other side of a forum to be clear what a person is asking about. In this case I could just include the links to the two github repositories as examples of what I was trying to do. I posted it and didn’t hear anything back on the day. The next morning I woke up and saw that at 3am a Redhat Engineer in China had forked my project and provided a fix. Immediately I could see what I was missing and he made my test pass right away. Back in the day I probably would have given up and just gone Atomikos, but with github it is so easy to share sample code of what you are trying to do and Spring boot makes it so fast to stand up a sample app there is really no reason not to do so anymore.

 One more note while I was working on this experiment in testing how to configure different JTA managers the Narayana guys submitted code to Spring Boot 1.4 Milestone 2 to include a Narayana Quickstarter so now it will be possible to easily wire that into a Spring Boot app. I know I talk about the greatness of Spring Boot all the time, but once again it saved me a ton of time by allowing me to prototype out a few options before I go too far down the road of solving the problem, and with github allowing me to collaborate with people around the world, we truly live in some amazing times.

Spring Boot and Security using Spring Data JPA for authentication

Recently one of my friends was working on a Spring Boot project and he was having trouble finding an example of how to configure user login for his site with Spring Boot using JPA. I had mentioned that there is some mention of configuring security in Greg Turnquist’s book Learning Spring Boot. He had just purchased Spring Boot in Action and I don’t think he was rushing to grab another book, but he hadn’t been able to find a good online tutorial.

Today I was browsing Twitter and I came across exactly what my friend was looking for. Priyadarshini B wrote a great online tutorial on doing just that on her blog. The post was so great I wanted to share it. So head over there and check it out, you won’t be disappointed as it will walk you through the whole process.

JavaMug Spring Boot Discussion

I attended JavaMug last Wednesday as the speaker was Craig Walls author of Spring Boot in Action. When I heard about the book I had planned on purchasing it, but was disappointed there was no kindle version on Amazon. It does state if you purchase the print edition they will give you the kindle one for free, but I am trying to move away from paper books in general.

Overall the talk was pretty good. It is nice that there is a Pivotal employee local to the area so we can get a talk like this done. For most of the talk Craig just sort of demonstrated examples of what you can do with Spring Boot since there were people of varying degrees of experience with it. It was held at Improving in Addison which I had never been to, but they had some nice beer on tap (Kentucky Bourbon Barrel Ale). In a talk like this where you are just trying to introduce the concept to people it is hard to get as deep of a dive as I would like. But I did enjoy the part of the demo playing around with the metrics. That is something I haven’t really played around with, but of course got me immediately thinking about how much I would like to use that at work. I think maybe this year I will attempt to convert our legacy app to Spring Boot. It will be painful, but it just seems like more and more the benefits are so good that is what we should be doing. Hopefully I can find the time at work.

Then at the end of the talk they did a raffle and lo and behold I won the digital copy of Spring Boot in Action. I was pretty stoked about that given that I wanted that originally to begin with. When they get it to me and I get a chance to read it I will post a review up here.

Spring Boot Actuator Guide

One of the most interesting Spring Boot features to me is the Spring Boot Actuator. I just love the concept of having all these restful endpoints to get useful operational data right out of the box. One issue I have had is that I don’t actually know all the endpoints just a few that I have used here and there. Today I saw a link to the Complete Guide for Spring Boot Actuator which is a pretty amazing post that covers everything and anything that you would want to know. The purpose of this post is just so I can go back and find this data later. If you are playing around with Actuators go and check out this post.