<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Flipp Engineering - Medium]]></title>
        <description><![CDATA[Insights from the engineers at Flipp - Medium]]></description>
        <link>https://medium.com/flippengineering?source=rss----2562f761b615---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Flipp Engineering - Medium</title>
            <link>https://medium.com/flippengineering?source=rss----2562f761b615---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:44:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/flippengineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ruby, Protobuf and the Schema Registry]]></title>
            <link>https://medium.com/flippengineering/ruby-protobuf-and-the-schema-registry-eaecac8e252e?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/eaecac8e252e</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Daniel Orner]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 13:50:18 GMT</pubDate>
            <atom:updated>2025-08-25T13:50:18.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o4wo_kYw4jkImApK" /></figure><p>At <a href="https://corp.flipp.com/">Flipp</a>, we make extensive usage of a few technologies which historically haven’t had the best of teamwork:</p><ul><li><a href="https://www.ruby-lang.org/en/">Ruby</a>, which we build most of our back-end administrative tools in;</li><li><a href="https://go.dev/">Go</a> which most of our end-user-facing systems are written in;</li><li><a href="https://kafka.apache.org/">Kafka</a>, which we use to send events and entities across microservice boundaries;</li><li><a href="https://protobuf.dev/">Protobuf</a>, which we use to strongly type our API’s (mainly via <a href="https://grpc.io/">gRPC</a>);</li><li><a href="https://avro.apache.org/">Avro</a>, which we use to strongly type our Kafka messages using…</li><li>the <a href="https://docs.confluent.io/platform/current/schema-registry/index.html">Confluent Schema Registry</a>, which provides a way to more succinctly encode each message and allow tools like <a href="https://lenses.io/">Lenses</a> to view and manage data.</li></ul><p>Previous ventures in marrying these technologies have resulted in some nifty tooling investments. Some of these include:</p><ul><li><a href="https://github.com/flipp-oss/deimos/">Deimos</a>, which provides a framework to integrate Avro and relational databases into the way we use Kafka in Ruby services;</li><li><a href="https://github.com/flipp-oss/grpc-rest">grpc-rest</a>, a way to use strongly-typed gRPC endpoints and have them also support JSON REST format in Rails;</li><li>kafka.go, an internal tool which provides some simple patterns to convert unstructured messages into schema-registry aware Avro messages in Go services.</li></ul><h3>The Protobuf move</h3><p>Protobuf in particular is a newcomer to this toolbox, resulting from our forays into gRPC. Protobuf has a number of advantages over Avro, even though they kind of do the same thing (i.e. validating and binary-encoding data using a schema). For example:</p><ul><li>Protobuf has strong tooling for generating code in any number of languages, including Go and Ruby. Once generated, this code is strongly typed and can be used as-is without having to worry about any kind of conversion.<br>– This support is much wider than that for Avro. We added some code to <a href="https://github.com/flipp-oss/deimos/?tab=readme-ov-file#generated-schema-classes">generate strongly typed Ruby classes</a> from Avro schemas, but it’s very bespoke and we’re likely the only folks using it.</li><li>Protobuf has an excellent registry called <a href="https://buf.build/">buf</a>. Buf allows consumers of a schema not to have to have the schema in the repo at all — command-line tooling allows you to generate the code you need without having to read the schema live, and without having to check anything into git. You just use a <a href="https://buf.build/docs/configuration/v2/buf-gen-yaml/">YAML configuration file</a>, and it’s downloaded at Protobuf compile time.</li><li>In general, Protobuf has much broader support and usage than Avro, and is a lot more popular in 2025.</li></ul><p>So it was almost inevitable that we’d start to investigate what it might look like to switch from Avro to Protobuf in our Kafka messages. Turns out, it needed a bit more work than we thought.</p><h3>An introduction to Kafka and the Schema Registry</h3><p>It’s important to understand a few things about how your message gets into and out of Kafka while using the Schema Registry.</p><p>Kafka messages (and message keys) are always stored as <strong>bytes</strong>. This means that any serialization you use will always end up as bytes. Tooling sometimes obfuscates this.</p><p>Let’s take a look at how a message might be encoded using Avro to start with.</p><p>With the following Avro schema:</p><pre>{<br>  &quot;namespace&quot;: &quot;com.my-namespace&quot;,<br>  &quot;name&quot;: &quot;MySchema&quot;,<br>  &quot;type&quot;: &quot;record&quot;,<br>  &quot;doc&quot;: &quot;Test schema&quot;,<br>  &quot;fields&quot;: [<br>    {<br>      &quot;name&quot;: &quot;test_id&quot;,<br>      &quot;type&quot;: &quot;string&quot;<br>    },<br>    {<br>      &quot;name&quot;: &quot;some_int&quot;,<br>      &quot;type&quot;: &quot;int&quot;<br>    }<br>  ]<br>}</pre><pre># Ruby<br>schema = Avro::Schema.parse(File.read(&#39;spec/schemas/com/my-namespace/MySchema.avsc&#39;))<br>stream = StringIO.new<br>writer = Avro::IO::DatumWriter.new(schema)<br>dw = Avro::DataFile::Writer.new(stream, writer, schema)<br>dw &lt;&lt; {test_id: &#39;some-string&#39;, some_int: 54}<br>stream.string</pre><p>The result looks like this:</p><pre>&quot;Obj\u0001\u0004\u0014avro.codec\bnull\u0016avro.schema\x94\u0003{\&quot;type\&quot;:\&quot;record\&quot;,\&quot;name\&quot;:\&quot;MySchema\&quot;,\&quot;namespace\&quot;:\&quot;com.my-namespace\&quot;,\&quot;doc\&quot;:\&quot;Test schema\&quot;,\&quot;fields\&quot;:[{\&quot;name\&quot;:\&quot;test_id\&quot;,\&quot;type\&quot;:\&quot;string\&quot;,\&quot;doc\&quot;:\&quot;test string\&quot;},{\&quot;name\&quot;:\&quot;some_int\&quot;,\&quot;type\&quot;:\&quot;int\&quot;,\&quot;doc\&quot;:\&quot;test int\&quot;}]}\u00004\xE4x\xD3g[\xCD\xE8Tp\xA1أHV\xED&quot;</pre><p>Note that this adds <em>the entire schema</em> as part of the encoded file. The actual encoded payload is the bytes at the end.</p><p>Using the schema registry, we can replace that entire schema with just a single number. This requires encoding the data differently. In Ruby, we can use the <a href="https://github.com/dasch/avro_turf">avro_turf</a> gem to do this:</p><pre>data = {test_id: &#39;some-string&#39;, some_int: 54}<br>AvroTurf::Messaging.new(registry_url: &#39;http://127.0.0.1:8081&#39;, schemas_path: &#39;spec/schemas&#39;).<br>  encode(data, schema_name: &#39;MySchema&#39;, namespace: &#39;com.my-namespace&#39;, subject: &#39;MyTopic&#39;)</pre><p>When this code is run, AvroTurf will <strong>register</strong> the schema with the registry, by passing the full text of the schema to be stored:</p><pre>POST http://127.0.0.1:8081/subjects/MyTopic-value/versions<br>{ &quot;schema&quot;: &quot;  {\n  \&quot;namespace\&quot;: \&quot;com.my-namespace\&quot;,\n  \&quot;name\&quot;: \&quot;MySchema\&quot;,\n  \&quot;type\&quot;: \&quot;record\&quot;,\n  \&quot;doc\&quot;: \&quot;Test schema\&quot;,\n  \&quot;fields\&quot;: [\n    {\n      \&quot;name\&quot;: \&quot;test_id\&quot;,\n      \&quot;type\&quot;: \&quot;string\&quot;,\n      \&quot;doc\&quot;: \&quot;test string\&quot;\n    },\n    {\n      \&quot;name\&quot;: \&quot;some_int\&quot;,\n      \&quot;type\&quot;: \&quot;int\&quot;,\n      \&quot;doc\&quot;: \&quot;test int\&quot;\n    }\n  ]\n}\n&quot;}</pre><p>This returned the value {&quot;id&quot;: 3}, indicating that the registry is storing this schema with an ID of 3. The <strong>subject</strong> of the schema in this example was given as MyTopic-value . Generally you want the subject name to match the Kafka topic, so you&#39;d have {topic_name}-value and {topic_name}-key schemas.</p><p>The result:</p><pre>&quot;\u0000\u0000\u0000\u0000\u0006\u0016some-stringl&quot;</pre><p>What does this mean? Confluent’s <a href="https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/index.html#wire-format">wire format</a> documentation gives us the info we need:</p><ul><li>The very first byte is a “magic byte” of 0, indicating this is a schema-registry-enabled message.</li><li>The next 4 bytes hold the schema ID, encoded in <a href="https://lemire.me/blog/2022/11/25/making-all-your-integers-positive-with-zigzag-encoding/">zig-zag notation</a>. In the above case, this is schema number 3 (0006 is 3 in zig-zag). So essentially, the next number is simply the ID of that schema in the schema registry.</li><li>The remaining bytes are the same encoded payload we saw earlier. (Ruby prints it out differently, but it’s the same bytes.)</li></ul><p>This cuts down the size of the message significantly, and allows us more easy visibility on the topic contents. Tools like Lenses integrate with the schema registry to display decoded data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-GUo3oeKW0CYQ_5c2bVUw.png" /></figure><h3>Now what about Protobuf?</h3><p>Protobuf is a more complex schema language than Avro. One of the simplest additions is imports. You can split up your schema among different files and import them, similar to fuller programming languages like JavaScript. You can also reuse these imports across different files — so, e.g. if you have a common structure representing a set of dates, you can include it in multiple entities that all share that set.</p><p>An example:</p><pre># simple/v1/simple.proto<br>syntax = &quot;proto3&quot;;<br>package &quot;simple.v1&quot;;<br><br>message SimpleMessage {<br>  int32 test_id  1;<br>}</pre><pre># complex/v1/complex.proto<br>syntax = &quot;proto3&quot;;<br>package &quot;complex.v1&quot;;<br><br>import &quot;simple/v1/simple.proto&quot;;<br><br>message ComplexMessage {<br>  simple.v1.SimpleMessage simple = 1;<br>  string some_string = 2;<br>}</pre><p>So that’s one complication — the schema registry won’t allow you to register a Protobuf schema unless it already has all the dependencies registered under matching subjects. In the schema registry, you have to pass it a set of references, including the subject and version, in order for it not to crap out at your import declarations.</p><p>In the below example, we first register simple.proto , as it has no dependencies, and then complex.proto , since it has a dependency on simple.proto .</p><pre>POST http://127.0.0.1:8081/subjects/simple%2Fv1%2FSimpleMessage/versions<br>{ <br>  &quot;schema&quot;: &quot;  syntax = \&quot;proto3\&quot;;\npackage \&quot;simple.v1\&quot;;\n\nmessage SimpleMessage {\n  int test_id  1;\n}\n&quot;, <br>  &quot;schemaType&quot;: &quot;PROTOBUF&quot;<br>}</pre><pre>POST http://127.0.0.1:8081/subjects/complex%2Fv1%2FComplexMessage/versions<br>{ <br>  &quot;schema&quot;: &quot;  syntax = \&quot;proto3\&quot;;\npackage \&quot;complex.v1\&quot;;\n\nimport \&quot;simple/v1/simple.proto\&quot;;\nmessage ComplexMessage {\n  simple.v1.SimpleMessage simple = 1;\n  int some_int = 2;\n}\n&quot;, <br>  &quot;schemaType&quot;: &quot;PROTOBUF&quot;, <br>  &quot;references&quot;: [<br>    {<br>      &quot;name&quot;: &quot;simple/v1/simple.proto&quot;,<br>      &quot;subject&quot;: &quot;simple/v1/simple.proto&quot;,<br>      &quot;version&quot;: 1<br>    }<br>  ]<br>}</pre><p>The second complication has to do with the fact that you can have multiple messages defined in a single proto file:</p><pre>syntax = &quot;proto3&quot;;<br><br>package referenced.v1;<br><br>import &quot;simple/simple.proto&quot;;<br><br>message MessageA {<br><br>  message MessageAA {<br>    string name = 1;<br>    simple.v1.SimpleMessage simple = 2;<br>  }<br><br>  message MessageAB {<br>    string name = 1;<br>  }<br>}<br>message MessageB {<br><br>  message MessageBA {<br>    string name = 1;<br>    simple.v1.SimpleMessage simple = 2;<br>  }<br><br>  message MessageBB {<br>    string name = 1;<br>  }<br>}</pre><p>The wire format requires that the bytes after the schema ID represent the indexes of the message in the proto file. If you’re using the very first message, you can just write 0, but anything else needs the array length followed by the messages you follow. So an encoding of a MessageBB would require you to write [2, 1, 1] (2 is the length of the array, 1 is the index of MessageB in the file, 1 is the index of MessageBB in MessageB). All numbers are still using zigzag encoding, like the schema ID.</p><pre>msg = Referenced::V1::MessageB::MessageBA.new(<br>      simple: Simple::V1::SimpleMessage.new(name: &quot;my name&quot;)<br>    )<br>encoded = proto_turf.encode(msg, subject: &quot;referenced&quot;)</pre><pre>&quot;\u0000\u0000\u0000\u0000\u0014\u0004\u0002\u0000\u0012\t\n\amy name&quot;</pre><p>In this case, byte 0 is the magic byte, schema ID is 7 (0 0 0 14), then it’s followed by [2, 1, 0] (array length 2, second message in the file, then first message in that message), followed by the encoded protobuf.</p><h3>proto_turf: Ruby’s Protobuf + Schema Registry Client</h3><p>I started work on a gem called <a href="https://github.com/flipp-oss/proto_turf">proto_turf</a>, designed to register Protobuf schemas and encode/decode messages. It’s named after avro_turf, which did more or less the same thing for Avro and has been around for a long while.</p><p>The main thing I worked with was the Protobuf <a href="https://github.com/protocolbuffers/protobuf/blob/v30.2/src/google/protobuf/descriptor.proto#L104">descriptor definition</a>. This, along with the DescriptorPool class in Ruby, gave me enough power to work with the messages that were being passed in to register with the schema registry. (Documentation is pretty bad on the Ruby side, but hopefully soon <a href="https://github.com/protocolbuffers/protobuf/pull/21212">it’ll improve</a>. Buf’s <a href="https://buf.build/docs/reference/descriptors/#deep-dive-into-the-model">descriptor documentation</a> was invaluable here.)</p><p>In particular, I was able to use FileDescriptor.dependency to walk the tree of all known file imports. Each file descriptor also has a name representing its import path. As long as the directory path matches the import path (and it has to, for protoc to work), I can just read the .proto file from disk and send it to the registry. And since I can walk the dependency tree depth-first, I can ensure that all dependencies are registered before the top-level schema I&#39;m working with.</p><p>So far so good! But there’s one more, insidious complication. With Avro, it’s unlikely you’ll be using it without the original schema files living in your repo. With Protobuf, and particularly with buf, you can pull in dependent protos without actually having the text in your repo at all! But the text - the contents of that .proto file - are what the schema registry expects to see.</p><p>In Go (the first language of Protobuf) everything is visible and doable, including <a href="https://pkg.go.dev/github.com/jhump/protoreflect/desc/protoprint">generating a </a><a href="https://pkg.go.dev/github.com/jhump/protoreflect/desc/protoprint">.proto definition from an actual Protobuf object</a>. Both Go and Java have built-in classes that automatically register Protobuf schemas with the registry using this sort of approach. But Ruby&#39;s generated Protobuf objects are opaque and there&#39;s no existing method to generate a .proto file from them. What do we do with Ruby?</p><h3>Attempt #1 — protoc-gen-schema-registry</h3><p>My first thought was to simply have a command-line tool that would read all the .proto files in the current repo and register them with the schema registry. We&#39;d have to run this tool on all the upstream dependency repos before any of the downstream ones could use the schema registry.</p><p>I’ve reached for the protoc plugin approach in the past - such as when <a href="https://github.com/flipp-oss/protoc-gen-avro">generating Avro from Protobuf</a>. The nice thing about it is that you can tell which .proto files are actually being generated and which are dependencies. I <a href="https://github.com/flipp-oss/protoc-gen-schema-registry">whipped up something</a> using Go (which has lots of Protobuf functionality). It worked!</p><p>But… it kind of sucks. There are now these extreme dependencies on services that you don’t necessarily own. You need to rely on them to run this script as part of CI, even if your downstream repo is the only one that actually needs to register it on the schema registry. Is there a better way?</p><h3>buf export</h3><p>Turns out there is! A coworker suggested I use <a href="https://buf.build/docs/reference/cli/buf/export/">buf export</a>, which I’d never heard of. What does it do? Why, it outputs all the dependencies that buf has downloaded into nice .proto files that your code can now read.</p><p>… 🤦‍♂️</p><p>So, goodbye protoc-gen-schema-registry, we never really needed you in the first place.</p><p>With buf export, all the .proto files go into your disk and look just like your own. I found out the hard way that these <em>can&#39;t</em> share a root directory with your protos, or your protos will simply be emptied out of their contents. (It would also complicate the protoc workflow since it wouldn&#39;t know which protos are yours and which aren&#39;t.)</p><p>I had to make changes to Deimos, the Ruby + Kafka library, to support multiple paths for Protobuf in order for this to work. But it did! Again! And everything was fine, except that in CI you had to remember to run buf export before running your application, and you had to add them to .gitignore , and your devs had to rerun it when using the schema registry. 😞</p><h3>Attempt #3: Dynamic! 🪄</h3><p>That was before I had a weird idea. <em>Somebody</em> wrote the code to generate those .proto files from the in-memory code. That&#39;s not built into the C library - the protoprint library I linked above was done manually. Couldn&#39;t I do the same? It likely didn&#39;t have to completely 100% match the original proto definition - there are a lot of features we didn&#39;t use, and we could always improve the generation over time.</p><p>How hard was it? Turns out it took me less than two days.</p><p>I often enjoy generating one version of a schema or code from another one. There’s something satisfying knowing exactly what your input and output should be from the start. And it was kind of fun delving into the full protobuf definition and seeing what features are in there that I’ve never used.</p><p>I’m still missing some things, but I got a working version: <a href="https://github.com/flipp-oss/proto_turf/blob/main/lib/proto_turf/proto_text.rb">voila</a>. No need at all for original .proto files - everything gets generated on the fly, regardless of where the relevant protobuf message came from. I ripped out the Deimos changes I made that needed multiple paths — au contraire, we now don’t need to give the Protobuf schema backend any paths at all!</p><p>One wrinkle is that I did <em>not</em> implement a way to <em>read</em> the proto definition back into a dynamic object. The simple reason is that Ruby flat out can’t do this. The proto ➡Ruby generation has to happen in C, and we’re not going to do that on the fly — it’s designed to happen only once, at compile time.</p><p>The good news is that all I <em>really</em> need to do is find the message in the descriptor pool and pull it out. In other words, do a quick mini-parse of the text to the find the namespace and message name of <em>any </em>message in the proto text, look that up in the DescriptorPool, get the file descriptor, then <a href="https://github.com/flipp-oss/proto_turf/blob/main/lib/proto_turf.rb#L174">walk the tree</a> using the indexes to identify the right message.</p><p>The main use of storing the full schema in the registry is to help with <a href="https://docs.confluent.io/platform/current/schema-registry/fundamentals/schema-evolution.html">backwards compatibility</a> . However, Protobuf is a lot more lenient than Avro in this regard, and the in-memory messages themselves do a lot of the heavy lifting in terms of coercion and compatibility. The benefit of strictly creating a schema from the one on the registry is lessened, and I opted not to worry about it. (Seems like the Confluent Python library <a href="https://github.com/confluentinc/confluent-kafka-python/issues/845#issuecomment-621223621">had the same idea</a>.)</p><h4>Wrapping Up</h4><p>proto_turf is out there and ready to be used, and Deimos is on deck to make use of it. Ruby’s finally ready to join the other big kids in having full support for Protobuf on the schema registry!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaecac8e252e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/ruby-protobuf-and-the-schema-registry-eaecac8e252e">Ruby, Protobuf and the Schema Registry</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Centralizing Your Docker Dependencies]]></title>
            <link>https://medium.com/flippengineering/centralizing-your-docker-dependencies-dd6c537ced4d?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/dd6c537ced4d</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[Daniel Orner]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 15:54:16 GMT</pubDate>
            <atom:updated>2021-07-26T15:53:58.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*5H70BMDY-8JFlRfv.jpg" /><figcaption>Image from <a href="https://pixabay.com/photos/port-pier-cargo-containers-crate-1845350/">Pixabay</a></figcaption></figure><p>Developing with <a href="https://docs.docker.com/get-started/overview/">Docker</a> is a great way to standardize your dependencies and make the development process less painful. Docker is a way to create lightweight virtual machines, or <em>containers</em>, to run programs from a known state.</p><p><a href="https://docs.docker.com/compose/">Docker Compose</a> is a feature of Docker. It’s a neat tool that allows you to spin up an entire application with all its dependencies in a single click.</p><p>There are a few different ways you can use Docker Compose in your local development. I’m going to present two ways I’ve seen, and then show you a third way which I feel gives you the best of both worlds.</p><h4>The Kitchen Sink approach</h4><p>Probably the most common way of using Docker Compose is to put both your application and all its dependencies in a single Compose file. For a Rails app with a Postgres database, it might look something like this:</p><pre>version: “3.9”<br>services:<br> db:<br>   image: postgres<br>   volumes:<br>     — ./tmp/db:/var/lib/postgresql/data<br>   environment:<br>     POSTGRES_PASSWORD: password<br>   expose:<br>     — “5432:5432”<br> web:<br>   build: .<br>   command: bash -c “bundle exec rails s -p 3000 -b ‘0.0.0.0’”<br>   volumes:<br>     — .:/myapp<br>   ports:<br>     — “3000:3000”<br>   depends_on:<br>     — db</pre><p>Now, by running docker compose up -d, you start up both the database and your app, in its own mini-network. The app uses portsto expose its port 3000 to the local machine, while the databases uses expose to only expose its 5432 port within the Docker network; it’s encapsulated away and unreachable from your local host.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*7gh_OUC7ni5MPQI_RBdOaw.png" /></figure><h4>The “What You Need” approach</h4><p>A second way of using Docker is to <strong>only use Docker Compose for dependencies</strong>, but leave the app itself out of your configuration. On the one hand, you do lose the convenience of “one-click” development. On the other hand, it’s much easier to do things like hot reloading and running IDE debuggers if you don’t have to squeeze past Docker to do it. There are also performance concerns, especially on Mac OS.</p><p>In this case, your file would <em>only</em> have the DB entry and not the web app:</p><pre>version: “3.9”<br>services:<br> db:<br>   image: postgres<br>   volumes:<br>     — ./tmp/db:/var/lib/postgresql/data<br>   environment:<br>     POSTGRES_PASSWORD: password<br>   ports:<br>     — “5432:5432”<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*HANwJM0iJ8anMTgu9MDVtw.png" /></figure><p>Here, your app is running on your local host, <strong>outside</strong> the closed network. So your database has to expose its 5432 port to the local host itself so your app can access it, using the ports declaration.</p><h4>Working with Multiple Repositories</h4><p>When you’re in the microservice world (assuming you have multiple repositories), using Docker Compose helps to standardize your development process. However, if you have your application inside your Docker network (using the Kitchen Sink technique), you end up having to have multiple copies of all your dependencies, especially if you work with many apps that resemble each other.</p><p>Taking the above examples, if you are working on two different services, each of which want to talk to a database, you would need to spin up two databases, one for each service, neither of which can talk to each other. If you have more dependencies (such as <a href="https://redis.io/">Redis</a>, or a messaging platform like <a href="https://kafka.apache.org/">Kafka</a>), you’re going to have more and more containers you need to manage, gobbling up resources on your computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*RSyZxgVAxp8hS3Pp5SIrZQ.png" /></figure><p>However, if you use the “What You Need” approach, where all ports are exposed to the host, you run into port conflicts. If your Docker Compose file belonging with System 1 tries exposing port 5432, and so does the one belonging to System 2, one of them simply won’t start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*KC6iGmZM_Mg0oOrfCTeZJg.png" /></figure><p>Another important note is that <em>neither</em> of these two methods allow you to do some kinds of integration testing — for example, if you use Kafka as a message bus, you have no way of having your first app send a message which your second app receives, because in both methods, they each have their own Kafka cluster which doesn’t talk to the other one.</p><h4>Centralizing Your Dependencies</h4><p>Really what you need is a recognition that there are a limited number of dependencies across all your services, and create a <strong>single, centralized</strong> Docker Compose file, outside all of your project folders (perhaps in your home directory). This file can include all possible dependencies for all possible projects, and you can bring them all up with a single docker compose up. All your apps can then connect to the exposed ports normally and transparently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*sc52okqyBdlWng7E67Wt_A.png" /></figure><p>Now, both apps can share a database (and any other resources they may need) on your local machine. You have one “global” dependency that all your applications can use since all ports are exposed. To ensure isolation, each app can (for example) create a separate database schema in the shared database.</p><p>However, this now individualizes the development process. Since the file lives outside any individual repo, there needs to be some kind of documentation telling new team members how to get it all started.</p><h4>Tool-erizing the Solution</h4><p>As with many things in life, things become easier for people if you build tools enabling them to be easier. In this case, we created a tool in Go called <a href="https://github.com/wishabi/global-docker-compose">global-docker-compose</a> (I know, original). This tool can be installed using Homebrew, so any dev can install it with a single command, and acts as a centralized dependency repository.</p><p>The idea behind this is that while all dependencies are <strong>defined</strong> in the tool, the service decides which dependencies it <strong>cares</strong> about. It does this via a single shell file that lives in the repo that does nothing but call the global-docker-compose tool with a set of arguments representing the services it cares about. A sample file might look like:</p><pre># gdc<br>global_docker_compose --services=postgres,kafka &quot;$@&quot;</pre><p>Once this file is created, the development process is as simple as calling gdc up, gdc down, etc. If you have multiple projects, running gdc up will bring up only the containers each project cares about. There are additional convenience commands for starting a MySQL or Redis client, for example. The tool is really not much more than a wrapper around Docker Compose, so it can merge config files, show logs, and more.</p><h4>Comments?</h4><p>We made this tool specifically for the dependencies that we use in our group at Flipp. However, you can fork it and update its Compose file to more closely match what your own team uses.</p><p>What do you think? Would your team benefit from a workflow like this?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd6c537ced4d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/centralizing-your-docker-dependencies-dd6c537ced4d">Centralizing Your Docker Dependencies</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using rubocop-ast to transform Ruby files using Abstract Syntax Trees]]></title>
            <link>https://medium.com/flippengineering/using-rubocop-ast-to-transform-ruby-files-using-abstract-syntax-trees-3e352e9ac916?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/3e352e9ac916</guid>
            <category><![CDATA[parsing]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rubocop]]></category>
            <dc:creator><![CDATA[Daniel Orner]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 14:01:03 GMT</pubDate>
            <atom:updated>2020-08-13T14:01:03.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*hktTsskEfFtnCUhE.jpg" /><figcaption>Image from <a href="https://pixabay.com/photos/small-toy-figurine-cartoon-3871893/">Pixabay</a></figcaption></figure><p>Sometimes as you go about your business of being a software engineer, a problem crops up that is unusually interesting, potentially really useful, and also seems like it should be relatively easy to do, given the age of your chosen programming language and the tools already available.</p><p>Such a situation happened recently with the introduction of a new “item indexer” project at Flipp. This was an attempt to replace a patchwork of existing systems that fetched item information from retailer websites with a single microservice that could do it for all requests.</p><p>So far, so groovy — but if we were going to create a unified service, we had to figure out what to do with all the existing indexers we had written in a variety of ways. Every retailer website is different. Some are well-designed, and contain common information in easy-to-read <a href="https://ahrefs.com/blog/open-graph-meta-tags/">OpenGraph headers</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop">itemprop properties</a>. Many others, though, don’t provide readily available information in nicely semantic tags, and instead we need to rely on xpaths that look like .//div[@class=&#39;col-right&#39;]/div[@class=&#39;product-desc&#39;]/h1 .</p><p>By the time we were ready to start the unified indexer project, the count of patchwork indexers was in the hundreds.</p><p>The new indexer service had a slightly different format than the old one, largely because we’d moved from the (now out-of-date) <a href="https://github.com/watir/watir">Watir</a> gem to <a href="https://github.com/teamcapybara/capybara">Capybara</a>. So… either we spent days manually rewriting each indexer to adhere to the new format, or we tried doing something a bit smarter.</p><h3>The Changes</h3><p>Here are some of the major changes we were trying to achieve:</p><pre># Module nesting<br>module ContentAggregation       -&gt;        module Indexers<br>  module JSParsers                          class MyRetailer &lt; Base<br>    class MyRetailer &lt; Base                  ...<br>     ...                                    end<br>    end                                   end<br>  end<br>end</pre><pre># Method renaming<br>def supplemental_info_price   -&gt;       def base_price<br>   ...                                   ...<br>end                                    end</pre><pre># Rename browser methods<br>page.at_xpath(&quot;an_xpath&quot;)      -&gt;   page.find(&quot;an_xpath&quot;)<br>page.xpath(&quot;an_xpath&quot;)         -&gt;   page.all(&quot;an_xpath&quot;)<br>div.inner_text                 -&gt;   div.text</pre><pre># Replace unnecessary blank checks, handled by new framework<br>a.blank? ? a : nil             -&gt;  a</pre><h3>Attempt 1: gsub!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*SInF0mwZs8Ngk93d.jpg" /></figure><p>The first attempt at translating the indexers was just to use good old gsub and regular expressions. This can actually get us pretty far! It’s pretty good at replacing the top part of each file (the module declaration). However, it relies heavily on every item indexer being written exactly the same way, including spacing, which may or may not be true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea15528873b3b9f3ad13f1d4971dda0a/href">https://medium.com/media/ea15528873b3b9f3ad13f1d4971dda0a/href</a></iframe><p>One of the big shortcomings is how we’re replacing all instances of end sandwiched by newlines with nothing, and assuming that the only case of that would be the one that ends the module (since we’re reducing nesting by one level). That’s pretty dangerous!</p><p>Also note that we didn’t even attempt to do things like replacing the blank check with nil, because of the different variations on spacing and things like that. We could try to spend a lot more time making it more robust, but we’d still have a hard time (e.g.) matching the start of methods to their ends.</p><h3>Attempt 2 — Climb the Tree</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*7jMcjEIEqlbADj06.png" /><figcaption>Image from <a href="https://pixabay.com/vectors/ecological-leaf-leaves-nature-2026102/">Pixabay</a></figcaption></figure><p>Instead of trying to blindly change the text of the Ruby file, I thought it would be much more powerful if we could instead parse and understand the Ruby code itself, and output changes to it. I knew that <a href="https://github.com/rubocop-hq/rubocop/">Rubocop</a>, the Ruby linter and formatter, does that with its auto-correct (where e.g. it can change find to select or vice versa), so it has to be possible somehow, right?</p><p>An <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree"><strong>Abstract Syntax Tree</strong></a> (AST) is an internal representation of a piece of code. It’s not specific to Ruby; every language has its own AST as an important step on the way to turn text into machine code. I figured the best way to be sure that I was changing things correctly would be to have some way to key into the AST of the code and make changes at the tree level.</p><h4>The Options</h4><p>The first result on Google for “ruby parse code” is the <a href="https://github.com/whitequark/parser">parser</a> gem, a well-maintained library for parsing Ruby code. It even comes with <a href="https://www.rubydoc.info/github/whitequark/parser/Parser/TreeRewriter">rewriting</a> capability! However, I found the documentation difficult to get through, and there didn’t seem to be a simple example for reading a file, changing it, and writing it back out.</p><p>I figured I’d try to find something maybe a bit more high-level to work with. The next candidate I found was <a href="https://github.com/xinminlabs/synvert">synvert</a>, which provides the ability to create “snippets” to transform code. This powers <a href="https://github.com/yujinakayama/transpec">transpec</a>, a great tool that converts <a href="https://relishapp.com/rspec/">RSpec</a> 2 syntax into RSpec 3.</p><p>Unfortunately, after playing around with this, it turned out it was a little <strong>too</strong> high-level. When working with very simple replacements, the <a href="http://xinminlabs.github.io/synvert/dsl/">DSL</a> seems like it would be a great match, but once you go past straightforward insertions or replacements, it becomes unwieldy fast.</p><figure><a href="https://github.com/rubocop-hq/rubocop"><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*50FL8mFDZUZu79Vd.png" /></a></figure><p>After taking a step back, I thought about the original inspiration for this idea, which was Rubocop. How does Rubocop actually do all of its (very complex, at times) rewriting? There are hundreds of “cops” which auto-correct, with dozens of contributors, so there must be an understandable way to write this code! Turns out, it uses good old parser under the hood, but with some additions that make it much sweeter.</p><p>In fact, the Rubocop project made so many enhancements to parser that they extracted them to a separate gem, <a href="https://github.com/rubocop-hq/rubocop-ast">rubocop-ast</a>. To understand why it’s so much easier to work with, let’s dive into how parser represents some simple Ruby code:</p><pre>def increment(x=1)<br>  x + 1<br>end</pre><pre>-&gt;</pre><pre>(def :increment<br>  (args<br>    (optarg :x<br>      (int 1)))<br>  (send<br>    (lvar :x) :+<br>    (int 1)))</pre><p>The indented syntax is compact but hard to read, so here’s what a tree version might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*zTDMhso4_ZFymCa5U4yqMQ.png" /></figure><p>The blue boxes with bold text represent literals (symbols, integers) while the rest represent nodes.</p><p>When I started looking at this, I was kind of overwhelmed. What is an lvar? (<em>Answer: Left-hand-side variable in an assignment.</em>) Where’s the block representing the actual method definition? (<em>Answer: Since it’s a single line, it doesn’t have one.</em>) Where are the symbols like ( and =? (<em>Answer: They aren’t represented in the tree at all.</em>) Digging deeper — if I only want to trigger a change on . and not &amp;. null-safe nodes, how do I ensure that? (<em>Answer: They are separate node types, </em><em>send and </em><em>csend.)</em></p><p>More of a problem is that the number of <a href="https://github.com/whitequark/parser/blob/master/doc/AST_FORMAT.md">node types</a> in parser are staggering. Node types are defined semantically rather than syntactically, meaning that the if node could represent an actual if statement, or a ternary ( foo ? 1 : 0 ), and only by inspecting the node children could you figure out which one it was.</p><p>rubocop-ast builds on top of the parser gem in two major ways. One is the introduction of specialized Node classes, with a huge number of semantic methods that allow you to more naturally deal with nodes when you have them. For example, the IfNode comes with a ternary? expression, which tells you by inspecting its children whether it’s a ternary or not; the class or module nodes have parent_class methods letting you reference the parent of the declaration.</p><p>The second addition is the <a href="https://github.com/rubocop-hq/rubocop-ast/blob/master/docs/modules/ROOT/pages/node_pattern.adoc">NodePattern</a> DSL, which is an XPath-like syntax allowing you to match a particular node against a pattern. Both of these are extensively used in Rubocop cops. I didn’t find NodePattern very comfortable, as it reminded me too much of regular expressions, which I find more difficult to reason about than actual code.</p><p>Although rubocop-ast is a great tool, its documentation was somewhat lacking. In particular, I still couldn’t find a good example of how to rewrite a file. Thankfully, the code itself was understandable enough for me to piece together the right way to do it. In addition, the amount of time I spent poring over the parser docs led me to create a new exhaustive <a href="https://github.com/rubocop-hq/rubocop-ast/blob/master/docs/modules/ROOT/pages/node_types.adoc">documentation page</a> for rubocop-ast listing the nodes by type (rather than mapping Ruby features to nodes as in the parser docs).</p><h3>Rewriting Code</h3><p>With all that said, how do you actually use rubocop-ast to rewrite code? There are two important parts to the parser gem that are critical to this: TreeRewriter and Source::Map .</p><p>Each node has a Source::Map you can access by calling node.location (or node.loc). This object is a mapping of AST nodes to actual source code. For example, taking the above example of Ruby code:</p><pre>def increment(x=1)<br>  x + 1<br>end</pre><p>The send node representing the single statement in the function would have the following source map:</p><ul><li>expression: 21..26 , source: x + 1</li><li>selector: 23..24 , source: +</li></ul><p>Each node type will have different location keys depending on what it is (so for example, an if node might have question and colon keys for ternaries). Note that e.g. the expression key includes child nodes as well. Having this information gives us a lot of power by being able to insert, delete or replace content around any individual part of this particular node.</p><p>That’s what TreeRewriter is for — once you have one set up, you can use its methods to change the source code by giving it a rangethat references the source. The cool thing about TreeRewriter is that it’s incredibly smart about how to change the code. Each change is put into a queue, and the changes are executed bit by bit, ensuring that the intention of the change isn’t modified.</p><p>For example, you could replace the + with a plus method, and then also add a space before the 1. Here’s a bad way to do that which only records the indexes where you want the changes to happen:</p><pre>123456789<br>x + 1 (the 1 is at char 5)<br>x plus 1<br>x pl us 1 &lt;&lt;- OOPSIE</pre><p>With TreeRewriter, all changes happen relatively, and are replayed correctly:</p><pre>123456789<br>x + 1<br>x plus 1<br>x plus  1</pre><h3>The Solution</h3><p>Without further ado, here’s what I landed on for my rewriting project. I created a number of processors called Rules, one for each change I wanted to do. I left it up to the TreeRewriter to process them and make sure they didn’t clobber each other. This is just three of the rules I made, but the great thing about this design is that I can make as many as I like and it’ll keep on truckin’!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5755b4d5bcc7887775bddbc7e8d44235/href">https://medium.com/media/5755b4d5bcc7887775bddbc7e8d44235/href</a></iframe><p>I felt like this combination of tools gave me the power I needed with the ease of use so that other people could look at the code and not be incredibly confused. I’m happy with what I landed on and hope people find it useful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e352e9ac916" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/using-rubocop-ast-to-transform-ruby-files-using-abstract-syntax-trees-3e352e9ac916">Using rubocop-ast to transform Ruby files using Abstract Syntax Trees</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Schema and Topic Design in Event-Driven Systems (featuring Kafka!)]]></title>
            <link>https://medium.com/flippengineering/schema-and-topic-design-in-event-driven-systems-featuring-kafka-a555ddfdb8d8?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/a555ddfdb8d8</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[schema]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[avro]]></category>
            <dc:creator><![CDATA[Daniel Orner]]></dc:creator>
            <pubDate>Fri, 01 May 2020 15:41:44 GMT</pubDate>
            <atom:updated>2020-05-01T15:41:44.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*6DDlUWJryTAlerFJ.jpg" /><figcaption>Image from <a href="https://pixabay.com/illustrations/network-internet-communication-3357642/">Pixabay</a></figcaption></figure><p>In the microservices world, communication between services provides a host of problems — one of them being “how do we ensure that the contract between services doesn’t break as those services change?”</p><p>Communication in event-driven land usually happens through some kind of messaging system. Here at Flipp, we’ve standardized on <a href="https://kafka.apache.org/">Apache Kafka</a>, a streaming platform with a <a href="https://medium.com/flippengineering/using-kafka-as-a-data-backbone-part-1-8316ab7db5e0">number of advantages</a> which have seen it play a central role in our architecture. This system will have a number of <strong>topics</strong> (also known as queues, buses, etc. in other products), each of which have a number of <strong>messages</strong> (records, events, etc.)</p><p>The way to enforce a communication protocol with services using a messaging system is by using a <strong>schema</strong>, a strongly typed description of your data. You encode your data using the schema on the input side, and decode it on the output side. If any data doesn’t match the schema, you can’t even encode it in the first place. You can think of schemas in messaging as analogous to interfaces in object-oriented design.</p><p>There are a number of schema formats, including Google’s <a href="https://developers.google.com/protocol-buffers">Protocol Buffers / Protobuf</a> (primarily used for RPC calls), and <a href="https://json-schema.org/">JSON Schema</a>, which can be used for Ajax requests. In the Kafka world, the “winner” for schema validation and encoding has generally been <a href="https://avro.apache.org/">Apache Avro</a>. This is the format used in a number of Confluent tools, including <a href="https://docs.confluent.io/current/connect/index.html">Kafka Connect</a> and most Kafka topic viewers. <em>(Hot off the press: </em><a href="https://www.confluent.io/blog/introducing-confluent-platform-5-5/"><em>Confluent just added support for Protobuf and JSON!</em></a><em>)</em></p><p>I’d like to explore the different categories of topics and provide some advice and best practices when crafting your <strong>schemas</strong>, as well as how to design what goes into your <strong>topics</strong> that the messages with those schemas are in.</p><p>Note that although I’ll be using Avro in this discussion, almost everything I say can be applied to Protobuf, JSON Schema, Thrift, etc. — they’re all pretty similar. There are also a couple of other streaming products similar to Kafka, but we’ll be using Kafka in all our examples here.</p><h4>Topic Best Practices</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/0*hbGdV0Z_4WfPkR3i.jpg" /><figcaption>Image from <a href="https://pixabay.com/photos/junction-box-assembly-product-solar-3482687/">Pixabay</a></figcaption></figure><ul><li><strong>Every message in a topic should be encoded with the same schema.</strong> This enforces the fact that the topic should represent one type of thing. Mixing types of data in a single topic pollutes the mental model of what that topic means.</li><li>In most cases, you’ll want to have <strong>exactly one producer and one or more consumers. </strong>If more services need to send the same kind of data, that’s a clue that your service boundaries are not well-drawn, or that one service should be talking to the other one in some different way instead. This applies to event, entity and response topics (see below).</li><li>In some cases, you should have the opposite: <strong>one or more producers and exactly one consumer. </strong>This applies to request topics (see below), ensuring only one system processes each request. You can think of it as a funnel instead of a branch-out.</li><li>Standardize your topic names to make it a no-brainer when creating new ones. One possible format is {BoundedContext}.{Subdomain}. For example: Orders.OrderCreatedEvent , Customers.ContactInfo , Geography.ZipCode.</li></ul><h3>Topic Design</h3><p>One great feature that Kafka has over many other streaming / messaging platforms is the concept of a <strong>message key. </strong>I go into more detail about it <a href="https://medium.com/flippengineering/using-kafka-as-a-data-backbone-part-1-8316ab7db5e0">here</a>, but associating a key with each message allows you to <strong>compact</strong> your topic so only the latest message with a given key exists and all previous messages with that key are automatically deleted. Generally the message key should be some kind of <strong>identifying ID</strong> (e.g. widget ID, order ID, etc.).</p><p>In the rest of this article, I’ll refer to message keys as just plain <strong>keys.</strong></p><p>Without further ado, let’s dive into the different types of topics and some things you should know about designing and using them.</p><h4>Event Topics (“this thing happened”)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*_PsYLpqFlxTK3a2A.jpg" /><figcaption>Image from <a href="https://pixabay.com/photos/admission-coupon-admit-carnival-2974645/">Pixabay</a></figcaption></figure><p>The important thing to note about event topics is that <strong>things can happen multiple times</strong>. An order can be edited many times; a product can be added, then added again so that there are two products in the order.</p><p>Because of this, event topics are “insert only” — you can’t represent the <strong>current</strong> state of anything using them. If you want to figure out the current state, you would need to use an <a href="https://martinfowler.com/eaaDev/EventSourcing.html">event sourcing</a> strategy, which is really only ideal for specialized cases.</p><p>Events are great for things like beacons and user actions (which you can run analytics queries on), or for a <strong>choreography architecture</strong> — triggering actions based on things that happen.</p><p>Messages in events should:</p><ul><li>Not have any keys associated with them — each event needs to be unique.</li><li>Have a <strong>retention policy or TTL —</strong> events should be automatically deleted after a certain period of time. You should be saving your events into long-term storage as they happen rather than keeping them in the topic.</li><li>Include all possible data that can act as a <strong>dimension </strong>when querying: User ID, order ID, customer ID, event type and subtype, etc. Once events have happened they can’t re-happen — and some dimension information may be different later, such as a user changing address — so try to include as much information about it as you can.</li></ul><h4>Event Types</h4><p>During design, you may find yourself in a situation where you have a number of events which all look exactly the same and have the same information:</p><ul><li>Order created: has a user ID, order ID, timestamp</li><li>Order began processing: Ditto</li><li>Order completed processing: Ditto</li></ul><p>The question is, when do you combine all of these into <strong>one topic with an event type</strong>, and when do you separate them into <strong>multiple topics? </strong>You need to ask yourself a few questions to decide this:</p><ul><li><em>Are we tracking the state of a single thing?</em> Using a single topic can help determine the final state, and also allows you to have a consistent partition for all related events. Assuming you’re producing your events in the correct order, this means you can also enforce ordering on the consumer side, so that you never process a “completed processing” event before a “began processing” event for the same order.</li><li><em>Will we work with these events all together?</em> If we want to combine a set of beacons into a single query (e.g. “get me all actions that happened to a order”), you’ll have an easier time with a single topic. If they’re always separate, it’s cleaner to have different topics.</li><li><em>What additional parameters does each event need?</em> If “order processed” has a number of additional fields which would be meaningless for “order created”, that’s a clue that they need to be separated out.</li><li>You may actually want <strong>three</strong> topics — one for “order created”, one for “order processed”, and one much simpler one for all “order events”. You could send both at the same time, or have a downstream service collating both topics into one.</li></ul><h4>Request and Response Topics (“do this thing / this thing is done”)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ws0VU01g4IYQGWD1_TaWRg.png" /><figcaption>Image from <a href="https://pixabay.com/vectors/arrows-blue-double-reverse-redo-151635/">Pixabay</a></figcaption></figure><p>Request and response topics are similar to event topics. The main difference is in the <strong>meaning</strong> of the topic.</p><p>Events (pub/sub style) contribute to a <strong>choreography</strong> architecture —each service <strong>publishes</strong> things that happen and interested downstream services <strong>subscribe</strong> to those events and react accordingly.</p><p>On the other hand, requests and responses are an <strong>orchestration </strong>strategy — when a service knows something must happen, it explicitly asks the downstream service to perform it. Often there is a single orchestrator service performing a number of requests to different downstream services.</p><p><a href="https://blog.bernd-ruecker.com/why-service-collaboration-needs-choreography-and-orchestration-239c4f9700fa">There are pros and cons to both strategies.</a> In general, when service A not only wants service B to do something, but is interested in the results, request/response is a better choice than pub/sub.</p><p>Like event topics, requests and responses should not have message keys, and should have a TTL / retention period. The differences are:</p><ul><li>Events represent actions that happen in a system, and are prime candidates for analytics queries later on — hence my suggestion to include as much information as possible. Requests, on the other hand, only should include whatever information the downstream service needs to do its job.</li><li>Requests should have some kind of “request ID” (also known as a “correlation ID”) which the downstream service will retain and send back in the response. This ensures that responses can be associated with the original request, and also helps with tracing and debugging.</li><li>If a service can respond to requests from multiple sources, it’s a good idea to identify the source service with a string or ID of some kind, and pass that back as well. This way the originating service can easily filter out responses that aren’t meant for it. Alternatively, make separate topics for each requesting system (although that makes the requested service more tightly coupled with the requesters).</li></ul><h4>Entity Topics (“here is this thing”)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7HmjlZyuxmmdRPw-zS9pg.png" /><figcaption>Image from <a href="https://pixabay.com/illustrations/announce-marketing-attention-3192838/">Pixabay</a></figcaption></figure><p>These topics represent the latest state of a particular entity, with all its current information. I go into more depth <a href="https://medium.com/flippengineering/using-kafka-as-a-data-backbone-part-1-8316ab7db5e0">here</a> as to how you can use these topics to form a “data backbone” for your architecture. The main point is that you use message keys to identify the entity you’re dealing with, and you ignore (or delete) all messages with the same key except the latest one.</p><p>Entity topics can be considered a “public view” into one or more tables in a local database. Exposing this data via Kafka allows other systems to read the data into their own data stores and perform operations or queries on it.</p><p>Entity topics can be considered “upserts” — they should be sent whenever:</p><ul><li>An object is created</li><li>One of the fields <strong>in the topic schema</strong> changes on that object</li><li>The object is deleted (in Kafka, you’d send a null payload with the same message key).</li></ul><p><em>Shameless plug — if you’re using Ruby, </em><a href="https://github.com/flipp-oss/deimos/"><em>Deimos</em></a><em> does a great job of managing entity topics!</em></p><p>Entity topics in the world of the data backbone should be created:</p><ul><li>When a downstream system has need of the data</li><li>When people need to run queries on that data in a reporting data structure like a data lake (assuming data gets into that lake via your messaging service)</li></ul><p>For entity topics, you should be adding <strong>as little as possible</strong> to your topics. Find out what your consumers need and don’t add anything else, even if it’s tempting (and encouraged by tools like Kafka Connect) to just dump your entire database table to your topic. Adding fields is easy; removing them is very hard, as it’s difficult to figure out who is using a field and why.</p><p>Most importantly: <strong>Do not mirror your database schema in your topics.</strong> Your internal schema is used internally. This is a public interface read by people who know nothing about how you work. Use nested records instead of one per table; ignore internal fields that aren’t immediately obvious; ensure your data is clean; and don’t produce more messages than downstream customers care about.</p><p>Sometimes you might need an “internal topic” for use within a set of microservices that you own, as well as an “external topic” for use outside your team. You can either send both of them from the same source, or consider a “sieve” or “gatekeeper” service that intercepts all internal topics, cleans up and sanitizes the data, and produces a set of topics that external teams can understand and use without asking questions.</p><h4>When do I make a new topic?</h4><p>One of the common questions when working with entity topics is how much data to include in your topic, particularly when looking at has-many relationships. Do you totally normalize it and have many smaller topics? Or have multiple tables in one big topic?</p><p>Here are some rubrics for making this decision — assuming you already have a topic A (representing entity A) and you’re looking at adding information representing entity B, which has some kind of relationship with entity A:</p><ul><li>If B is <strong>interesting on its own</strong>, a new topic is probably a good idea. By “interesting”, I mean that there can conceivably be a service that cares <strong>only about B but not about A</strong>.</li><li>If the <strong>source</strong> of B data may change in the future (e.g. you are looking at breaking up a monolith and B would move to a microservice), you should make B its own topic. If A and B are part of the same bounded context and will always live together, it’s likely not necessary.</li><li>For <strong>performance</strong> purposes — if adding B to A would cause the messages to be too big or make it send messages unnecessarily. Remember that you’d need to send a new message when either B <strong>or</strong> A changes if they share a topic.</li></ul><h4>Examples — Translations</h4><p>In this case, we are using a library like <a href="https://github.com/globalize/globalize">globalize</a> to provide a has-many relationship with domain data — so a retailer might have an English, French, and Spanish name, for example. In our database, we represent this with two tables: retailers and retailer_translations .</p><p>Using the rubric above:</p><ul><li>Translations are not interesting on their own — no one would only want the translations without the retailer.</li><li>The source is not likely to change.</li><li>It won’t make a big change to the size of the message or update frequency.</li></ul><p>In this case, adding the translations to the existing schema (via a nested array) is the right choice.</p><p>The same thinking can often be applied to thumbnails, images or attachments associated with an object.</p><h4>Examples — Associations</h4><p>Think about something a bit more meaty, like a customer that has multiple orders. In this case:</p><ul><li>Some services might care about orders without knowing all the customer details.</li><li>It’s very likely that the thing that manages orders and the thing that manages customers might break apart in the future.</li><li>The update frequency might change a lot, and if we’re keeping a full order history, that would balloon the message size.</li></ul><p>In this case, it’s a no-brainer to separate them.</p><p>Other examples aren’t quite so straightforward, so try and figure out what belongs where using my suggestions above.</p><p>Note that sometimes the right solution is option 3 — have <strong>both</strong> topics. With Kafka, you can write joiners with Kafka Streams or KSQL to join two topics (although there are challenges with that approach). You can also have your current database send out both the “enhanced” and “separate” topics, since it’s often easier to join in a relational database than outside it. The main downside to this is that you now have two “sources of truth”, so you need to be extra careful about how you present these topics to your downstream consumers.</p><h3>Schema Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*jwLA061mztlhVY20.jpg" /><figcaption>Image from <a href="https://pixabay.com/illustrations/blue-cube-design-modern-cube-shape-2137334/">Pixabay</a></figcaption></figure><h4>A Quick Avro Introduction</h4><p>Like most schema formats, Avro has both <strong>primitive</strong> types:</p><ul><li>Numeric types: int, long, float and double</li><li>Strings and bytes</li><li>Booleans</li><li>Null</li></ul><p>…and <strong>complex</strong> types:</p><ul><li>Records (a type with predefined, named fields)</li><li>Arrays (lists of values)</li><li>Enums (a scalar value from a list of possible values)</li><li>Maps (key-value stores — a.k.a. dictionaries or hashes)</li><li>Unions (one of multiple types — this is used to allow nulls)</li></ul><p>Avro schemas can be nested by having types inside types (e.g. an array of records where each record has a field called “images” which is an array of strings).</p><h4>Schema Evolution</h4><p>One of the nice things about Avro is the fact that two schemas can be <strong>compatible</strong> even if they aren’t <strong>identical</strong>. This means that you can encode a message in version 1 of a schema and decode it with version 2, as long as you haven’t made any <strong>breaking changes</strong> in your schema in the meantime. Similarly, you can write using a newer version of the schema and read with an older version.</p><p>A great tool when using Avro with Kafka is the <a href="https://docs.confluent.io/current/schema-registry/index.html">Confluent Schema Registry</a>. This is a central place to hold your schemas, and allows you to encode and decode against the registry instead of a local schema. This not only shrinks the size of your messages, but also enforces schema <strong>evolution</strong> — you can’t make any breaking changes to a schema if that change is rejected by the registry.</p><h4>Breaking Changes</h4><p>In Avro world, a breaking change means:</p><ul><li>Adding a field without a default value</li><li>Removing a field without a default value</li><li>Changing a field’s type or name</li><li>Changing an enum’s values if it has no default enum symbol</li></ul><p>You can see a theme here — <strong>default values</strong> are incredibly important as a barrier against incompatibility. In general, all non-essential fields should have default values. Here, non-essential means <strong>a field which does not define the basis of the message</strong>.</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c78248ade691059e83e8f55e70a0a9a0/href">https://medium.com/media/c78248ade691059e83e8f55e70a0a9a0/href</a></iframe><p>In this case, widget_id is a basic field — you’d never describe a widget if it didn’t have one. On the other hand, color is a nice-to-have. Even if every single current consumer wants to know a widget’s color, widgets could stop being categorized by color, or others could lose interest in the color. Therefore, we give color a default value. In practice, very few fields should ever <strong>not</strong> have a default value.</p><p>Note that the default value is not an empty string, but a <strong>sentinel value</strong> we don’t expect to ever see. This is because the default value represents <strong>the value we see when our reader schema doesn’t even have this field — </strong>for example, if we decide to remove it. You’re going to want to use a sentinel value when <strong>an empty value has meaning. </strong>In this case, an empty color might mean that <em>no color was selected</em>, whereas the sentinel value indicates that <em>we don’t know anything about the color. </em>Downstream systems might handle these cases in different ways, so it’s important to differentiate.</p><p>On the other hand, if there’s no appreciable difference between the field being missing and the value being empty (for example, some freeform text like a description), feel free to use an empty string or null for a default.</p><h4>Schema Tips</h4><p>Here’s a quick list of suggestions for your schemas. Again, this is Avro-centric, but most if not all can be applied to other schema formats.</p><ul><li>Your schema is your service’s <strong>public interface</strong>. It’s how other services access your data, events, requests and responses. Design them <strong>for your consumers, not for you</strong>.</li><li>You can use your database schema as a starting point, but <strong>messages are not database tables.</strong> Just because your database has a field in a particular type does not mean your public schema should define it that way. Consider each field and type realistically — in what format do consumers want it? You might be using ints in your DB to represent a state, timestamps, etc., but downstream consumers will want string s or enum s to make it more understandable. Do your consumers really care about the created_at date of a record in your table?</li><li>Use longs instead of ints when defining identifying IDs (widget ID, order ID, etc.), wherever you can. You never know when your scale of data is going to explode, and changing it can be expensive. Another option is to use UUIDs instead of integer IDs, but that’s not always possible.</li><li>Add a timestamp — in <strong>human readable format</strong> — to all your schemas. When printing out your messages to logs, it becomes much easier to trace and debug. Computers can read human format, but humans can’t read UNIX timestamps.</li><li>Add a message_id to all your schemas, and set it to a UUID. This allows you to trace a message easily — e.g. figure out if service A sent it and service B didn’t receive it. Note that this is different from your identifying IDs — this is for debugging purposes only.</li><li>Most schema formats have a “doc” field for types allowing you to describe them. Use it. Document the meaning and use of your schema, and every single one of your fields. Don’t assume that because you know what it means that others will (or that <strong>you</strong> will in six months’ time). Document the possible values for fields, as well as what might cause those values to change.</li><li>If your field is a boolean type, don’t allow nulls. Just… don’t. They don’t make sense. If you need three values, make it a three-value enum — <a href="https://thedailywtf.com/articles/What_Is_Truth_0x3f_">where two of the values are <strong>not</strong> “true” and “false”</a>.</li><li>Allow nulls in your field <strong>if and only if null is a valid, meaningful value.</strong> If an empty string and null are always treated identically for a field, use a string type. Don’t allow null for any “required” field (i.e. if the field is in the schema, it must always have a value). Don’t add it in just because you forgot to add a “NOT NULL” to the corresponding database column.</li><li>Use enums for a <strong>limited, discrete set of values.</strong> Don’t use it for ranges of numbers. Don’t use strings or ints for this purpose. Remember to add a “default enum symbol” of a sentinel, similar to what you’d use for fields. <em>(Note that earlier versions of Avro had some challenges with enums — the introduction of default symbols has made them flexible enough to use safely.)</em></li><li><strong>Avoid unions</strong> for any purpose other than allowing nulls. It muddies the waters as to what the meaning of a field actually is. If you find you need a field to be one of multiple completely different types, a rethink is likely in order.</li><li>If you are using Avro and Kafka, schema-encode your keys as well as your payloads. This makes it much easier for strongly-typed languages like Java to manage your messages.</li></ul><p>Schemas are powerful and amazingly helpful to keep your data sane. Use them wisely!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a555ddfdb8d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/schema-and-topic-design-in-event-driven-systems-featuring-kafka-a555ddfdb8d8">Schema and Topic Design in Event-Driven Systems (featuring Kafka!)</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coupling in Microservices, Part 2: Single vs. Multi-Repo]]></title>
            <link>https://medium.com/flippengineering/coupling-in-microservices-part-2-single-vs-multi-repo-35c5d5f3057b?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/35c5d5f3057b</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Daniel Orner]]></dc:creator>
            <pubDate>Wed, 01 Apr 2020 14:08:26 GMT</pubDate>
            <atom:updated>2020-04-01T14:05:32.093Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous article, I discussed some of the advantages and disadvantages of single vs. multiple services. In this article, I’m going to assume that you went the multi-service route.</p><h4>Some Terms To Think About</h4><p>When we talk about “services”, there are actually multiple different things we can mean. (I know that these terms may not be the commonly used definitions!) In this article, I will be discussing three aspects of a service:</p><ul><li>A <strong>system</strong> is what I’ll be referring to a <strong>bounded context</strong> as. This can be a group of services working together to accomplish a common purpose, or a single service all on its lonesome. A Kubernetes pod can often be deployed as a system.</li><li>A <strong>service</strong> — in the Docker / container world — is a <strong>single process</strong>. This can be an HTTP service, a scheduled job, a message consumer, etc.</li><li>A <strong>repo</strong> is your actual source code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*KORGAIvrvk6nm69vKIBaWA.png" /><figcaption>A possible way to split up systems into multiple repos and repos into multiple services.</figcaption></figure><p>In our own tooling at Flipp, as of this writing we assume that <strong>all three of these are closely connected</strong>. One repo provides one service which is responsible for one system. However, I’ve started understanding the limitations of this mental model and wanted to explore the ramifications of it. Most importantly — does it make sense to have <strong>one repo per service</strong> or <strong>one repo per system?</strong> I take it as obvious that you <a href="https://www.infoq.com/news/2015/01/microservices-sharing-code/">should not be sharing code <strong>across</strong> systems</a>.</p><h4>New KPI’s to discuss</h4><p>In the previous article, I talked about KPI’s (Key Performance Indicators) and how I wanted to explore each KPI separately and see how one or multiple services affected each KPI in isolation. I’m going to do something similar now for one or multiple <strong>repos</strong>.</p><p>The same caveats apply as previously:</p><ul><li>Assume that the system uses some kind of relational database, although you can generally swap in a NoSQL or similar solution without much difference.</li><li>Assume that all services are in the same programming language. There’s really no reason <strong>not </strong>to use multiple repos if you’ve got different languages.</li></ul><p>(Note: one thing that can help to make multiple repos “more similar” to a single repo is tools like <a href="https://github.com/mateodelnorte/meta">meta</a> or <a href="https://github.com/ingydotnet/git-subrepo">git-subrepo</a>, which combines multiple repositories into a “parent” repo.)</p><h4>Speed of System Creation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZvEZGdVKf74L41fz" /><figcaption>Photo by <a href="https://unsplash.com/@sergeytrofimov?utm_source=medium&amp;utm_medium=referral">Serghei Trofimov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How fast can the system be written from scratch?</p><p>The more repos being created means more time to complete the project — any new repo has a non-zero setup time. There are two aspects to this:</p><ul><li>Creating a new repo and populating it with a boilerplate or bare-bones system that has the correct access pattern (HTTP API, delayed job processor, message consumer, etc.) but does nothing;</li><li>Shared business logic, schemas, etc. If you have more than one process that needs identical code, you’ll need to either a) copy/paste all the logic and make sure they stay in sync, or b) create a <strong>third</strong> repo to hold this logic and include it in the other two.</li></ul><p>This seems to indicate that even if it’s almost trivial to set up a new service, it may be beneficial to have those different services running from the same repo.</p><h4>Ease of Understanding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*X9GWxHGTpNhZRf2p.png" /><figcaption>Image from <a href="https://pixabay.com/illustrations/communication-head-balloons-man-1991851/">Pixabay</a></figcaption></figure><p>How quickly can someone understand your system — enough to answer questions about how it works?</p><p>This is possibly the KPI most open to interpretation and dependent on how good everything else is.</p><p><strong>In general</strong>, having multiple repos makes it harder to understand how everything works together:</p><ul><li>Figuring out what uses a particular function or class means you also need to know where the access points are (HTTP, message consumers, etc.) and which other service inside the system (or outside it!) calls them;</li><li>Tying together how a feature works across services means having to read/search through multiple repos and sets of code.</li></ul><p>If you have external documentation, or a consistent pattern (all HTTP services look like <strong>this</strong>, all delayed jobs look like <strong>this</strong>), you can mitigate some of the pains of having multiple repos. In addition, understanding a <strong>smaller piece</strong> of the puzzle (how <strong>this</strong> process contributes to the feature) can be easier when the repos are separate.</p><p>Of course single repos can easily be <strong>more</strong> confusing if they aren’t well-written. If you have spaghetti code where one piece of code affects five others when they have no business being anywhere near each other, you’ll run into more problems than you’ll solve. Multiple repos is a way of <strong>enforcing</strong> encapsulation; you need more discipline to enforce it in a single repo.</p><p>Long story short, bad code is bad code no matter where it is, but introducing multiple repos also introduces some level of additional complexity even with good code.</p><h4>Ease of Onboarding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*sdADp3ZN2PTUKcht.png" /><figcaption>Image from <a href="https://pixabay.com/vectors/airplane-jet-turbine-high-flight-2098593/">Pixabay</a></figcaption></figure><p>How quickly can a new team member start being productive?</p><p>Other than ease of understanding (above), the main determinator is how easy it is to set up their environment so they can verify that what they’re doing actually works.</p><p>For simple tasks, it can be faster to become productive when repos are separate. You only need to clone the repo you need to fix, and you (e.g.) don’t need to set up a local message broker if you only need to add a feature to the UI. If this is the bread-and-butter of your workload, multiple repos can be a fine choice.</p><p>For more complex tasks, though, where multiple areas of the system are affected, multiple repos become more challenging. You will need to clone several repos, set up your environment several times (e.g. running npm install ), and figure out a way to get your services talking to each other in your local environment. You may need a tool like rvm to install multiple versions of the same language or library if your services use different ones.</p><p>Using docker and docker-compose can make this easier and less error-prone, but comes with its own extra set of challenges, especially for junior devs, in terms of the extra layer of execution and understanding how to interact with containers. It also can be slower to run (especially on Macs) and harder to connect debuggers from your IDE’s.</p><h4>Feature or Bug Implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*U6P5fBRTw5nWmhj1.jpg" /><figcaption>Image from <a href="https://pixabay.com/illustrations/banner-header-beetles-insects-bugs-1711719/">Pixabay</a></figcaption></figure><p>How quickly can a defined problem be solved?</p><p>If the task is simple and the service responsibility is well-defined, fixing it in a single one of multiple repos can be faster, since the repo itself is smaller and easier to reason about.</p><p>However, if the task is larger, you’ll need to make changes in multiple places, put in multiple pull requests (each of which may have its own back-and-forth code review process) and likely have to do some kind of end-to-end test. In addition, your repos may have different language or framework versions, meaning context switching when fixing one or the other .</p><p>In a single repo, you’ll never need more than one pull request, one ticket to manage the process, and can likely write a unit or system test inside the same repo.</p><p>Having multiple repos can enforce encapsulation and make each area simpler to change — but you can get the same benefit by using a single repo that has well-defined code boundaries.</p><p>One downside of having a single repo is that you risk having your change affect other areas of the code inadvertently. If your system repo is relatively small, this is less of an issue; but if you start building up many services, you’d need tight unit tests with broad coverage to ensure that new features don’t break existing code anywhere else.</p><h4>Schema Migrations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*xrlo95951kyNjKaa.png" /><figcaption>Image from <a href="https://pixabay.com/vectors/arrows-adaptation-change-direction-709731/">Pixabay</a></figcaption></figure><p>How easy is it to make changes to how your data is structured?</p><p>If your system lives in a single repo, you only need to make the change in one place. Your unit tests will then automatically pass or fail and you can handle everything once.</p><p>If you have multiple repos, you’ll need to propagate the changes to each repo separately. Either you’ll need to copy/paste the changes, or you’ll have to have a shared library or sub-repo that has the changes, which will then need to be updated in all repos. This is not only more work that will take more time, but increases the chances that you’ll miss some service somewhere which will be using the wrong schema.</p><p>There are tools that can make this process easier, like the <a href="https://github.com/confluentinc/schema-registry">Confluent Schema Registry.</a> However, all this does is make sure that downstream systems don’t <strong>break</strong> if the upstream schema changes. It doesn’t actually propagate the changes down to other systems transparently.</p><h4>CI/CD Integration and Deploys</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*spTY-Eegp4CF8Kd_" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here, multiple repos come out the winner in terms of creating tooling in CI to run tests, do deploys, etc. It’s very easy to separate out deploys of different services if each service is in its own repo. It’s still possible to do it with a single repo, but you either have to deploy everything at once, or get clever (separate by directories, have a mapping file, require manual action) with your deploy process.</p><p>Note that running unit tests could be wasteful if using separate repos when one can do. Much of the time in CI is spinning up images, running dependencies like databases, installing packages, etc. If you could do that once and run your tests for all services in the same workflow, you’d save a lot of processing time and likely cost.</p><p>On the flip side, in single repo-land you could instead lose more time by running all your unit tests when you’re only changing some of the code.</p><figure><a href="https://xkcd.com/303/"><img alt="" src="https://cdn-images-1.medium.com/max/413/0*WGR3hJNx-iW3LfmT.png" /></a><figcaption>Tests running sir!</figcaption></figure><h3>Summary</h3><p>Each of these KPI’s have a lot of ifs ands and buts, which was largely my goal. As in all things software, there is rarely a clear winner for any given design. The answer to almost any architecture question is “it depends”.</p><h4>Advantages of Multi-Repo:</h4><ul><li>Enforces separation of concerns</li><li>Easier to understand individual pieces of the puzzle</li><li>Easier to make simple changes</li><li>Less chance that making changes will affect other code</li><li>Easier deploys in CI/CD</li><li>Faster unit test runs in CI when making smaller changes</li></ul><h4>Advantages of Single Repo:</h4><ul><li>Faster to create a new system</li><li>Faster to understand the system as a whole</li><li>Quicker onboarding / environment setup</li><li>Faster to begin investigating problems (not necessarily finding the solution)</li><li>Faster to make changes that affect multiple areas</li><li>Easier to make changes to schemas or shared business logic</li><li>Faster unit test runs in CI when making larger changes</li></ul><h4>In general</h4><p>My suggestion would be to use one repo for a bounded context except in the following situations:</p><ul><li>Your Continuous Deployment pipeline can’t handle the single-repo-multi-service pattern and isn’t flexible enough to build it in;</li><li>You don’t have broad coverage of unit tests in your code or the willingness to write them; or</li><li>You have multiple teams working on a bounded context at once and need to split that context down as much as possible to reduce the blast radius.</li></ul><p>As always, look at what’s important to you, what resources you have available and where you want to focus to decide what direction to go in.</p><h4>Summary — My Values</h4><p>I can’t speak for everyone at Flipp, but my own set of values could be described thusly:</p><ul><li>People cost more than machines. Reducing development time is one of the most useful things we can do.</li><li>Retaining people is important, especially retaining good people in today’s engineering market, where the average time at a company is two years. Things we can do to improve morale give a large benefit that often outweighs the downsides.</li><li>Being agile (in the sense of moving quickly) gives the team more freedom to create an architecture that actually maps to the problem they are trying to solve. If it takes a long time to spin up a new service, or there are technical limitations stopping that service from doing what it needs to do, we may find ourselves picking the “wrong” architecture to save time.</li></ul><p>Based on this, my order of operations for all the KPI’s mentioned in the last two articles would look something like:</p><ul><li>Ease of understanding</li><li>Ease of onboarding</li><li>Speed of system creation</li><li>Speed of feature/bugfix implementation</li><li>Ease of investigations and debugging</li><li>Ensure smooth schema migrations</li><li>CI/CD integration</li></ul><p>Based on this, my preferred (not only!) pattern would be to have a <strong>single-repo multi-service</strong> representation of a single bounded context system. This allows us to keep models and schemas shared, and have a single place to search, document and setup, but allow us to scale separately and reduce the blast radius. The downsides may be more difficult CI/CD integration and deploy logic, the possibility that a service may have access to resources it doesn’t need, and some lowered performance. I’m good with those given the advantages!</p><p><strong>What’s your priority list?</strong></p><p>I plan on also writing up some case studies about how we can use these KPI’s to drive design and architecture of a system — keep your eyes peeled!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35c5d5f3057b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/coupling-in-microservices-part-2-single-vs-multi-repo-35c5d5f3057b">Coupling in Microservices, Part 2: Single vs. Multi-Repo</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coupling in Microservices, Part 1: Single vs. Multi-Service]]></title>
            <link>https://medium.com/flippengineering/coupling-in-microservices-part-1-single-vs-multi-service-4204fd9a57e6?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/4204fd9a57e6</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Daniel Orner]]></dc:creator>
            <pubDate>Fri, 28 Feb 2020 16:34:17 GMT</pubDate>
            <atom:updated>2020-02-28T16:29:39.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Here at Flipp, we use <a href="https://dzone.com/articles/event-driven-microservices-patterns">Event-Driven Microservices</a> pretty heavily. In particular, we use Apache Kafka as our <a href="https://medium.com/flippengineering/using-kafka-as-a-data-backbone-part-1-8316ab7db5e0">data backbone</a>. Microservices are (from a historical perspective) a relatively new pattern in computer science. One of the main touted advantages of microservices is the ability to <strong>decrease coupling</strong> between different pieces of functionality.</p><p>“Low coupling” is a term <a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)">originally used</a> to refer to different modules or classes within a single codebase. More recently, it’s been co-opted to be used within a service-based architecture to discuss the advantages of keeping the different services independent.</p><p>Some of these advantages include:</p><ul><li>Reducing the “blast radius” of issues; if one service goes down, the others can stay up;</li><li>Reducing the things that need to be changed when making code changes (if something is independent then theoretically only that part of the code needs to be changed and deployed);</li><li>Ability to scale different parts of the code differently if they have different needs (e.g. we may need only one front-end UI container, but five backend API containers if there are other services calling it);</li><li>Each service focuses on a single task to make each piece more easily digestible by programmers and more easily testable;</li><li>Ability to limit the access requirements of each service to tailor it to its own needs (no need for a single service to access a database, a messaging topic, a Redis cluster, an external API, other HTTP services, etc.)</li><li>Ability to make changes more agilely (you can upgrade a library more easily if it’s used by less code).</li></ul><p>I’d like to take a deep dive into what low coupling means and how it translates to real-life improvements.</p><h4>What are we trying to improve?</h4><p>In software architecture, there are always a number of things to consider before choosing a design. Some of these are on the technical level (speed, cost, reliability) while others are on the human level (ease of understanding, maintainability). You can consider each of these areas as <strong>KPI’s</strong> (Key Performance Indicators) where we want to get the best possible result. Most KPI’s come with tradeoffs that need to be considered.</p><p>Standard caveats:</p><ul><li>I will be discussing a <strong>standard web application</strong> — let’s say hundreds of requests/messages per second, and tens of thousands of users.</li><li>Assume that the system uses some kind of relational database, although you can generally swap in a NoSQL or similar solution without much difference.</li><li>Assume that all services are in the same programming language.</li></ul><p>In each of the following sections, I will be focusing on <strong>a single KPI at a time</strong> (note that the absolute best thing for one KPI can be <strong>disastrous</strong> for a different one — I am not advocating for any of these local optima!) and discussing what variables can affect it.</p><h4>Speed and Performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rPYD7C8Zoo62a81G" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">chuttersnap</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>No matter what you’re doing, systems work faster if there’s zero network latency. A function call is always more performant than either synchronous (HTTP, RPC) or asynchronous (message broker/queue) messages. This seems to indicate that putting services that <strong>constantly talk to each other</strong> into the <strong>same process</strong> will be the best bet for performance. This is particularly true of synchronous API’s.</p><p>This does depend on scaling issues— if your single service is too beefy to be reasonably scaled, then splitting it up can increase total throughput even if an individual task may take longer.</p><p>Performance in a multi-service case can be increased by having your services all make their updates into a single data store. This way the updates can be seen immediately with no delay across all services. (Remember my caveat above though — there are plenty of reasons why this can be a terrible idea!)</p><p><strong>Cost</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TLxnIhyp9U3UHbOZ" /><figcaption>Photo by <a href="https://unsplash.com/@blankerwahnsinn?utm_source=medium&amp;utm_medium=referral">Fabian Blank</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Cost is completely dependent on how your services run. In some offerings, you’re essentially paying for your CPU time, so the number of services doesn’t matter as long as they’re all doing work. Other times you’ll need a consistent box to run your services on, and in that case it may or may not make sense to bundle multiple services together, depending on their resource costs.</p><p>In general in today’s market, engineer hours are orders of magnitude more valuable than CPU time, so this KPI is (and should be) often ignored until it gets out of hand.</p><h4>Blast Radius</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xhSs8PsuyhKBVDn4" /><figcaption>Photo by <a href="https://unsplash.com/@yoshginsu?utm_source=medium&amp;utm_medium=referral">Yosh Ginsu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If something goes wrong with Thing A, how likely is it that Thing B is also affected?</p><p>There are two aspects to this:</p><ul><li>Point of failure: If something goes down, does it affect something else?</li><li>Resource utilization: Can something grab all the memory or CPU and stop the other thing from doing its job?</li></ul><p>Here the clear winner is multiple services, full stop. Having two things running in the same container or process is a huge risk that introduces a single point of failure. Splitting out processes adds fault tolerance.</p><p>However, it should be noted that this only makes sense if those processes are truly <strong>independent</strong>. If (e.g.) one of them is a backend API and the other is a message broker that does nothing but call that backend API, you don’t actually gain any points of failure. (However, you do still get the advantage of separating resource usage.)</p><p>Another aspect to this is the ability to separate out the <strong>access permissions</strong> of each service. If only Service A needs to access the database, then denying Service B access to the database cuts in half the chances of introducing a bug that makes the database go crazy.</p><p>Figuring out what should be a separate process can be split down business lines (a problem with item reviews should not affect buying the item) as well as technical ones (a broken image processor shouldn’t affect the creation of the reviews).</p><h4>Scaling Efficiency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Un4VigwuROvX0h1m70JSw.png" /><figcaption>Image from <a href="https://pixabay.com/photos/escalator-stairs-metal-segments-283448/">Pixabay</a></figcaption></figure><p>Here again, multiple services are the clear winner — you can scale your HTTP API separately from your front-end and separately from your message broker. Assuming cost (above) is not an issue, this allows you to tweak your processing load so it’s perfect for each job.</p><h4>Ownership of Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXztlwnXGJFQ9mZToMoagw.png" /><figcaption>Image from <a href="https://pixabay.com/illustrations/tug-of-war-force-teamwork-men-rope-1013740/">Pixabay</a></figcaption></figure><p>How confident can we be that one system or service owns a particular kind of data?</p><p>One of the constant refrains of microservices is that you shouldn’t have two services writing to the same database. The question is — does this really mean two <strong>services</strong>, or two <strong>systems? </strong>(Many people use the term <strong>service</strong> to really mean a set of processes working together. I’ve been using it to refer to a single process, and the word <strong>system</strong> to refer to the set of processes.)</p><p>I argue that because systems consist of services that <strong>work together for a shared business purpose</strong>, it’s entirely proper that more than one service within the same system write the same kind of data. If the only real difference between service A and service B is that A is triggered by an HTTP request but B is triggered by a message on a queue, A and B should be treated as identical from a business point of view.</p><p>We don’t gain anything by tying our arms around our backs and forcing ourselves to create multiple data sources, pass the data around, etc., when all these services are managed by the same team and contributing to the same overall process — in fact, there are plenty of downsides to this which are covered by other KPI’s.</p><p>In other words, for this question I believe it makes no difference whether there are one or many services in a single system — the data ownership should be the same — on the <strong>system</strong> level.</p><h4>Speed of System Creation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZvEZGdVKf74L41fz" /><figcaption>Photo by <a href="https://unsplash.com/@sergeytrofimov?utm_source=medium&amp;utm_medium=referral">Serghei Trofimov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How fast can the system be written from scratch?</p><p>The main variable here is how good your tooling is in creating a new service. How much manual work is involved in creating tasks / lambda functions / etc., ensuring permissions are set correctly, setting up access rights, and all the other fun stuff?</p><p>The bigger the pain of setting up a new service, the more beneficial it is to bundle services together, e.g. by forking or threading.</p><h4>Investigations and Debugging</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*L3NSW9peoXOsk0Nv.jpg" /><figcaption>Image from <a href="https://pixabay.com/illustrations/scan-system-bug-virus-malware-3963099/">Pixabay</a></figcaption></figure><p>How quickly can problems be identified?</p><p>The fewer things you need to check, the better. This seems to point to a single service being the best of all worlds. Having multiple services that talk to each other can quickly lead you to a place where you need to start at the end and follow the trail all the way back till you see where the breakdown happened. (Service D got the message, did service C send it? No, so did service B send it? Yes, so something happened between B and C.)</p><p>However, putting multiple kinds of work into a single service can actually make it more confusing, not less (e.g. all your logs could be interleaved). Clean separation could give the investigation less cognitive overhead even if it takes longer to match up the streams.</p><p>Cross-service tracing tools like <a href="https://aws.amazon.com/xray/">AWS X-ray</a> can help making this kind of debugging problem easier.</p><h4>Maintenance Coverage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*V3RkVjeUhVCB-kne.png" /><figcaption>Image from <a href="https://pixabay.com/vectors/progress-bar-percentage-chart-data-4706330/">Pixabay</a></figcaption></figure><p>How many things do we need to monitor or support?</p><p>One of the big challenges with creating services is having to make sure the lights are on constantly. With a single service, you can set up a single monitoring account, ensure that one system has the right amount of CPU, memory, etc. More services mean more monitors, more alerts, more dashboards and more knowledge of what runs where.</p><h3>Summary</h3><p>Although in general multiple services have a number of advantages, the disadvantages shouldn’t be discounted. Some good advice is usually to start with a single service, design it in a way such that bounded contexts have bounded code boundaries, and split it up when it becomes too much to handle.</p><h4>Advantages of Multiple Services:</h4><ul><li>Multiple points of failure (if boundaries are drawn correctly)</li><li>Individualized resource utilization</li><li>Reduced possibility of shared resources being accidentally misused</li><li>Ease of scaling separately</li><li>Faster to investigate problems that are pegged to a single area/process</li></ul><h4>Advantage of Single Services:</h4><ul><li>Performance</li><li>Faster setup time (e.g. access control, permissions)</li><li>Can be simpler to investigate more complex problems</li><li>Less monitoring and alerting necessary</li></ul><h4>In general</h4><p>I’d recommend using multiple services only when:</p><ul><li>Your single service has shown some of the disadvantages listed above and it’s hurting you (too many points of failure, scaling issues, trying to do too much at once).</li><li>You have a good way of spinning up new services (and setting up permissions, access control, resources etc.) As of now most companies seem to have to spin up their own way to do this, although there are third parties that aim to simplify the process.</li><li>You have a good way for different services to talk to each other (e.g. Kafka or a good API framework and schema).</li><li>The services are doing wildly different things (e.g. database CRUD vs. image processing) or are acting on totally different types of data.</li></ul><p>Next up —a discussion of whether to handle your multi-service setup within a <strong>single</strong> code repository or have <strong>separate</strong> repos for each service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4204fd9a57e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/coupling-in-microservices-part-1-single-vs-multi-service-4204fd9a57e6">Coupling in Microservices, Part 1: Single vs. Multi-Service</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Deimos: Using Kafka as the Data Backbone for your Architecture]]></title>
            <link>https://medium.com/flippengineering/introducing-deimos-using-kafka-as-the-data-backbone-for-your-architecture-205bbc248391?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/205bbc248391</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Daniel Orner]]></dc:creator>
            <pubDate>Mon, 28 Oct 2019 19:59:13 GMT</pubDate>
            <atom:updated>2019-10-29T20:32:03.706Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*C23Mo5Zl0Lw33pOg" /></figure><p>In the <a href="https://medium.com/flippengineering/using-kafka-as-a-data-backbone-part-1-8316ab7db5e0">previous article</a>, I detailed the microservice pattern of using Kafka as a data backbone for your architecture — Kafka acts as the source of truth and each microservice consumes data from it. This allows each service to be independent and to own only the data it cares about. We also said that there should be some way to marry traditional relational databases like MySQL and Postgres with the Kafka data backbone with a minimum of fuss.</p><p>We left off with a couple of problems:</p><ol><li>Ensuring that downstream systems are not tied to your internal data schemas;</li><li>Fixing the transaction problem, where due to errors data can be written to Kafka or your database but not both.</li></ol><h4>Ruby on Rails — the Database Experts</h4><p>Here at Flipp, we use Ruby on Rails heavily for systems that talk to databases. Rails’s ActiveRecord package has been in active development for over 13 years, covers a wide range of features and has been battle-tested in thousands of applications. Rails allows us to talk to our database in a consistent way and abstracts most of the underlying details away for us.</p><p>When we started widely using Kafka in our engineering org, we quickly realized we needed a way to:</p><ul><li>Save data from Kafka to our database</li><li>Write data to Kafka — either updating state or sending events</li><li>Encode/decode data using Avro and the Confluent Schema Registry (a free centralized hub for all our Avro schemas)</li><li>Standardize logging and tracing for all our consumers</li></ul><p>Our first attempt to send data across systems was to use Kafka Connect. We ran into a number of problems with it, some of which were detailed in the previous article. We decided it was more prudent for us to strike our own way to solve this problem.</p><p>We started off with a shared library we called FlippRubyKafka in late 2017. Over the last two years, this library has grown, added features and fixed bugs and has powered over a dozen of our core microservices. We are happy to announce that this project, now called <a href="https://github.com/flipp-oss/deimos/">Deimos</a>, is now open source!</p><figure><img alt="Deimos logo" src="https://cdn-images-1.medium.com/max/139/0*K8YeGni4aDdvuDKr.png" /></figure><h4>Deimos Features</h4><p>Deimos is firmly designed to cut down as much as possible on boilerplate and plumbing code. It is focused entirely on the use case of Kafka as a data backbone with Avro composing the structure of the data.</p><p>Deimos is built on a previous, smaller library called <a href="https://github.com/phobos/phobos">Phobos</a> (<a href="https://en.wikipedia.org/wiki/Deimos_(moon)">hence the name</a>), which in turn is built on <a href="https://github.com/zendesk/ruby-kafka">RubyKafka</a>, a pure Ruby implementation of the Kafka client.</p><p>Note that Deimos assumes that you have a copy of the <a href="https://hub.docker.com/r/confluentinc/cp-schema-registry/">Confluent Schema Registry</a> running. If you’ve already got Kafka and Zookeeper up then all you need to do is deploy the Docker container to the cloud provider of your choice and get a reference to its URL.</p><h4>Configuring Producers and Consumers</h4><p>You can use Deimos simply as a way to tie Avro and Kafka together, and it works really well even if you’re not using Rails! Both producers and consumers allow your business logic to deal exclusively with Ruby hashes — they will automatically be encoded to and decoded from Avro via the schema registry before interacting with Kafka.</p><p>Because Avro is a central tenet of Deimos, all producers and consumers must specify which Avro schema and namespace they will use while consuming or producing. In addition, they need to specify how they handle keys for these messages:</p><ul><li>The default, and recommended, way to handle keys is to Avro-encode them. This allows for any downstream systems that use static types (e.g. those written in Java or Scala, which have a large ecosystem related to Kafka) to easily decode them.</li><li>You can also indicate that your topic has no keys (e.g. event topics should <strong>not</strong> have keys as you want to keep all events, not just the last updated state).</li><li>Finally, you can leave your keys as plaintext, although this is not recommended.</li></ul><p>When using Avro-encoded keys, you can provide a separate key schema, or you can have Deimos auto-magically create one for you from your value schema, by specifying a field (usually “id”) to extract from it.</p><p>Sample producer:</p><pre>class MyProducer &lt; Deimos::Producer<br><br>  namespace &#39;com.deimos.my-app-special&#39;<br>  topic &#39;MyApp.MyTopic&#39;<br>  schema &#39;MySchema&#39; # will search in the configured path<br>  key_config field: &#39;key_field&#39;</pre><pre>  def send_some_message(an_object)<br>      payload = {<br>        &#39;some-key&#39; =&gt; an_object.foo,<br>        &#39;some-key2&#39; =&gt; an_object.bar,<br>        &#39;key_field&#39; =&gt; an_object.my_field<br>     }<br><br>      self.publish(payload)<br>    end<br>  end<br>end</pre><p>Sample consumer:</p><pre>class MyConsumer &lt; Deimos::Consumer<br><br>  schema &#39;MySchema&#39;<br>  namespace &#39;com.my-namespace&#39;<br>  key_config field: :my_id <br><br> def consume(payload, metadata)<br>   MyHandlerClass.do_something_with(payload[:my_field], metadata[:key])<br>  end<br>end</pre><p>All schemas are automatically registered in the schema registry using the topic name (so if you produce to MyTopic, your schemas are automatically registered to MyTopic-keyand MyTopic-value.</p><h4>Producing to Kafka</h4><p>Deimos producers always produce to a given topic. Producers have a number of convenience features:</p><ul><li>You will get an automatically generated timestamp (current time) and message_id (uuid) in your payload, if they are present in the schema. This helps immensely when debugging messages across systems.</li><li>Types will be coerced before saving, so if your schema expects a string but you give it an int, you don’t need to worry about crashes.</li><li>Metrics are sent allowing you to track the messages you send per topic and partition, as well as tracing enabled to determine if encoding your message is slow.</li></ul><h4>Consuming from Kafka</h4><p>As with Phobos, Deimos creates a separate thread per consumer, where each consumer listens to a single topic. Metrics and tracing are used to track the number of messages consumed as well as how long they take to process, and there is a special “lag reporter” that sends metrics on the lag for each topic/partition being listened to.</p><p>Consumers will “swallow” errors by default (relying on tracing to handle alerting in this case) and move on, to prevent individual bad messages from blocking your consumer forever. You can change this behavior or define specific errors or situations where you would not want the consumer to continue.</p><h4>Working with Databases</h4><p>Although just including Avro will unlock a lot of potential, Deimos really starts to shine once you hook it up to a database via ActiveRecord. As with Avro, there are ActiveRecord versions of both producers and consumers:</p><ul><li>ActiveRecordConsumers essentially act as a “sink” — dumping a topic into a database table based on some business logic.</li><li>ActiveRecordProducers act as a “source” — taking in an ActiveRecord object and automatically turning it into a payload to be encoded and sent to Kafka.</li></ul><p>Sample ActiveRecordCosumer:</p><pre>class MyConsumer &lt; Deimos::ActiveRecordConsumer<br><br>  schema &#39;MySchema&#39;<br>  key_config field: &#39;my_field&#39;<br>  record_class Widget<br><br>  # Optional override to change the attributes of the record before <br>  # they are saved.<br>  def record_attributes(payload)<br>    super.merge(:some_field =&gt; &#39;some_value&#39;)<br>  end<br>end</pre><p>Sample ActiveRecordProducer:</p><pre>class MyProducer &lt; Deimos::ActiveRecordProducer<br><br>  topic &#39;MyApp.MyTopic&#39;<br>  schema &#39;MySchema&#39;<br>  key_config field: &#39;my_field&#39;<br>  record_class Widget<br><br>  # Optional override to change the default payload calculated from the record.<br>  def generate_payload(attributes, record)<br>    super.merge(:assoc_key =&gt; record.some_association.assoc_key)<br>  end<br>end<br><br>MyProducer.send_events([Widget.new(foo: 1), Widget.new(foo: 2)])</pre><p>In addition to the producer, Deimos also provides a mixin you can add to your ActiveRecord objects which will <em>automatically </em>send messages whenever your records are created, modified or destroyed (as long as you don’t use mass operations like update_all or import).</p><pre>class Widget &lt; ActiveRecord::Base<br>  include Deimos::KafkaSource<br><br>  def self.kafka_producers<br>    [MyActiveRecordProducer]<br>  end<br>  <br>end</pre><h4>Database Backend</h4><p>So we’ve got Deimos sending your database records out to Kafka and receiving messages and dumping them in. So far so good. But let’s take this one step further. In the <a href="https://medium.com/flippengineering/using-kafka-as-a-data-backbone-part-1-8316ab7db5e0">previous article</a> we discussed some of the issues with having both databases and Kafka in the same application — the problem of <strong>transactions</strong>.</p><p>You can read that article for more, but in a nutshell, we want a guarantee that every record written to the database has a corresponding Kafka message, and every Kafka message is written to the database.</p><p>Deimos achieves this with the <strong>database backend</strong>.</p><p>This feature transparently replaces the inline sending of Kafka messages to instead save them to a table in the database. There is then a separate process that reads the messages off this table and sends them off in batches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*WShFRj13-LadDNf7yKAcqg.png" /><figcaption>Top: Naive Kafka. Bottom: DB Backend pattern.</figcaption></figure><p>Enabling this feature is incredibly simple:</p><ol><li>Generate the migration to add the table.</li><li>Set the publish_backend configuration setting to :db .</li><li>Run the DB Producer in some way (forked process, thread, rake task) via Deimos.run_db_backend!.</li></ol><p>This is also known as the <a href="https://microservices.io/patterns/data/transactional-outbox.html">transactional outbox pattern</a> and achieves full transactional integrity. All messages (whether they represent changes to objects or events) are part of the same transaction and will only be saved if the transaction commits. If it rolls back, all messages will also roll back and not be sent.</p><p>Calling code doesn’t even need to know that the DB backend is turned on. You call the publish method on your producer the same way — instead of sending the message to Kafka directly, it will encode it and save it as a message in the database.</p><p>This feature is currently powering our largest producer of data and our production metrics show being able to send 4,000–6,000 messages per second with a single thread.</p><h4>Test Helpers</h4><p>Deimos comes with a robust suite of RSpec test helpers to allow you to test your business logic without having to actually set up Kafka and the schema registry for local testing.</p><p>Just include the TestHelpers module in your specs and automatically stub out all loaded producers and consumers:</p><pre>RSpec.configure do |config|<br>  config.include Deimos::TestHelpers<br>  config.before(:each) { stub_producers_and_consumers! }<br>end</pre><p>Consumers can be tested by passing a hash and the consumer class into a test method:</p><pre>expect(Widget.count).to eq(0)<br>test_consume_message(WidgetConsumer, {id: 5, name: &quot;Darth&quot;}, call_original: true)<br>expect(Widget.count).to eq(1)</pre><p>Producers can be tested by just sending messages normally and using the have_sent matcher:</p><pre>expect(&#39;widget-topic&#39;).not_to have_sent(anything)<br>Widget.update(:my_attr, 1)<br>expect(&#39;widget-topic&#39;).to have_sent(hash_including(:my_attr =&gt; 1))</pre><h4>What’s Next</h4><p>We’re just getting started with Deimos. We’d love to hear your use cases and feature requests, and we’ve got a <a href="https://github.com/flipp-oss/deimos/issues">bunch of our own</a> to start with and plenty of improving to do. We welcome your contributions and we’re excited to see how far this will go!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=205bbc248391" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/introducing-deimos-using-kafka-as-the-data-backbone-for-your-architecture-205bbc248391">Introducing Deimos: Using Kafka as the Data Backbone for your Architecture</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Kafka as a Data Backbone: Part 1]]></title>
            <link>https://medium.com/flippengineering/using-kafka-as-a-data-backbone-part-1-8316ab7db5e0?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/8316ab7db5e0</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Daniel Orner]]></dc:creator>
            <pubDate>Mon, 28 Oct 2019 19:58:30 GMT</pubDate>
            <atom:updated>2019-11-04T20:20:49.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*cAQ1JuTEuTuHqi3D.jpg" /></figure><p>Apache Kafka, a distributed, asynchronous streaming platform, has exploded in popularity over the last few years. It boasts a number of advantages, including fault-tolerance, availability, reliability and scalability, and is being used by hundreds of companies ranging from tiny startups to enormous companies like PayPal and Twitter.</p><p>In this article, I’ll describe how Kafka can be used to act as the data backbone for your microservice architecture, and provide a host of advantages while being able to solve many of the inherent disadvantages that come with that pattern. I’ll also cruelly hint at an awesome open-source toolkit we built that solves a big part of this but which will have an entire Part 2 dedicated to it. 😈</p><h4>Event-Driven Microservices</h4><p>First off — the use case we are describing here is for an ecosystem largely consisting of <strong>event-driven microservices</strong>. It’s beyond the scope of this article to dive deep into this pattern, but in a nutshell, we want to:</p><ul><li>Decrease coupling between features and services.</li><li>Allow different teams to work independently on unrelated features.</li><li>Allow services to scale independently.</li><li>Allow services to be deployed independently.</li><li>Enforce a strong contract via technology (instead of convention) so we can be largely confident in <strong>contract testing</strong> instead of <strong>integration testing</strong>.</li></ul><p>There are a number of challenges with this paradigm, though — in this article I’ll describe one way to use Apache Kafka to solve some of those challenges.</p><h4>The Data Backbone</h4><p>In order for our services to be able to do their jobs, they will have to do one of two things:</p><ol><li>Have all the data it needs to do its job, OR</li><li>Be able to ask some other service in real-time for the data it needs to do its job.</li></ol><p>Option 2 is the one mostly used by HTTP REST services. Unfortunately, this violates some of our goals above, notably decreased coupling and independence, since service B needs to know how to reach service A, and if service A goes down, service B now needs to handle that case.</p><p>Instead, our pattern is to <strong>copy all necessary data from service A into service B</strong>. This way, each service has immediate use of all the data it needs to do its job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*X0Tlx-tqfqyRKk79.jpg" /><figcaption>Just put all your data on the backbone!</figcaption></figure><p>Ignoring the increased use of disk space (which is really cheap nowadays), there are a couple of problems with this approach:</p><ul><li>How does service B get service A’s data? Having it talk directly to service A’s database is a no-no, since that violates independence yet again.</li><li>How can we ensure real-time (or close to real-time) updates of that data?</li><li>How can we make sure we don’t miss any updates?</li><li>How do we communicate the structure of the data (and changes to that structure) without being strongly coupled to the original service?</li></ul><p>Turns out, Apache Kafka and Apache Avro have some cool features that will help us achieve our goals and neatly bypass most if not all of our challenges.</p><h4>Upsert Messages</h4><p>Every message in Kafka has a <strong>key</strong> associated with it. This key by convention does <strong>not</strong> indicate the ID of the <strong>message</strong>, but of the <strong>entity </strong>represented by that message. This allows Kafka to contain “upsert” messages, where each message represents the <strong>current state of an entity.</strong></p><p>Kafka itself uses this idea in its compaction algorithms — if compaction is turned on, it will automatically delete all messages but the last one which share the same key. This allows new consumers to simply skip all previous updates of a particular entity and jump straight to its current state. A deletion can be indicated by sending the entity’s key with a null message.</p><p>For example, if you send a message on a Characters topic that says name: &quot;Luke&quot; with a key of 105, then a second message that says name: &quot;Darth&quot; with a key of 105, Kafka will eventually delete the first message and only leave the last, most updated one, giving Mr. 105 the name “Darth”. If you then send a null message with a key of 105, the last message will eventually be replaced with null, indicating Mr. 105 has been deleted (this is known as a “tombstone” message).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*Y7hz4gIebmHkdPozjlm-Hw.png" /><figcaption>Key compaction — old data is removed and only latest state remains.</figcaption></figure><p>It’s a small feature, but it has huge ramifications. It means you can use Kafka as <strong>the data backbone of your system — as a distributed, subscribable source of truth for any type of data. </strong>You can send the current state of any object and downstream systems will know to create, update or delete it as necessary (I explore this fully below).</p><p>This means you can use Kafka to tie together any number of smaller services, each with their own database, as long as those services send the updates of their data to Kafka individually (and Kafka is set to keep those messages around as appropriate).</p><h4>Structuring Your Data</h4><p>This only solves part of the problem, though. We want to have these messages represent our data for <strong>anyone</strong> who wants to read it. We don’t want to get into API hell where every downstream system needs to know about the system that generated that data so it can understand its structure. We want true independence.</p><p>What we really want is to impose some kind of schema on our messages so that not only are we sending updated state, we are also enforcing a contract between producers and consumers so that state is <strong>reliable</strong> and <strong>understandable</strong>. Also important is that the contract needs to be <strong>flexible</strong> so that we can update the producer in specific ways without immediately causing all our downstream producers to crash.</p><p>Enter Apache Avro. This specification not only defines a schema language, but also a binary encoding of that language so that downstream systems can deterministically decode the message to the schema.</p><p>Even better, it introduces the concept of “compatible” schemas, meaning that the schemas on the upstream and downstream systems <strong>don’t have to match exactly</strong> as long as they are compatible. Upstream systems are free to add fields and make changes, as long as those changes are done in a compatible way, and downstream systems don’t need to move to the new schema unless they need the new changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*TXqV_daVwv--vc2HZFsCLA.png" /><figcaption>Example of a compatible change — adding a new field with a default value.</figcaption></figure><p>The combination of Kafka and Avro provides a <strong>strongly structured, distributed data backbone for a set of microservices</strong>.</p><h4>Duplicating Your Data</h4><p>But if data is “owned” by Service A, but is needed by Service B, how does it get there? The answer is duplication of data. Service B contains some kind of materialization (in a SQL/NoSQL database, in memory, etc.) of the contents of a Kafka topic. This materialization is by definition <strong>ephemeral.</strong> At any time, a service should be able to blow away its materialization and reconstruct it from the Kafka topic. <strong>The topic is the source of truth of data — all materializations are a view into it.</strong></p><p>This allows each service to truly be independent. Because data gets into a service asynchronously, no service has a direct link to any other service. If your Orders service has to know about Users, and your Users service is currently down, the Orders service doesn’t care. Its data might be a bit out of date, but it reads it from its own materialization of that data. In fact, it doesn’t even know that a Users service <strong>exists</strong> —all it knows is that there is a Users <strong>topic</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*NhHaAspMcEW9qhy3FvP1TA.png" /><figcaption>Consuming services get information from their data stores, not directly from the producing service.</figcaption></figure><p>And because every message in the topic is encoded with the same Avro schema, it has a guarantee of what the contents of that topic look like — and because it provides its own reader schema, another guarantee that it’ll never crash when reading a message (assuming we don’t break the requirement that all messages in a topic are encoded with the same schema).</p><p>Now that’s all well and good. But how do we implement this “source of truth” in Kafka? What does it look like in the real world? More specifically, how does the data get <strong>into</strong> Kafka in a safe way?</p><h4>Kafka and State — Uneasy Allies</h4><p>The “ideal” state is one where <strong>all data is written to the topic first, and then read back into the service’s materialization of that topic</strong>. This means that even for producing services, there is no primary database or other state — the topic is everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*pbYDjs5LOj-_biFwqunhnw.png" /><figcaption>“Ideal” workflow — write to topic, then read it back to the data store.</figcaption></figure><p>In practice, this is hard to swallow. Confluent, who is the leading company in the Kafka business, provides some helpful tooling for JVM languages around this pattern (e.g. <a href="https://docs.confluent.io/current/streams/concepts.html#ktable">KTables</a> and <a href="https://www.confluent.io/product/ksql/">KSQL</a>), but it all masks the point that <strong>Kafka is always asynchronous — and sometimes synchronous things need to happen.</strong> Particularly, anything that’s user-facing will often need to render the most up-to-date state back to the user. There are a number of tactics to allow the pattern to still work in this case (add a throbber / Ajax request, use some kind of cache, etc.) but they all introduce a whole whack of complexity which honestly isn’t really needed.</p><p>What’s more, using Kafka as your single state is simply not always the best option. Relational databases are decades old, and there are hundreds if not thousands of tools and frameworks built around them. They are well understood, extremely performant for most use cases, and incredibly good at what they do. Most web frameworks assume some kind of transaction-enabled, SQL-based database to do what they need to do. We should be able to leverage this standardized technology <strong>and</strong> the new hotness of Kafka at the same time.</p><h4>Databases and Kafka</h4><p>There are two current leaders in the field of marrying databases and Kafka: Confluent’s <a href="https://docs.confluent.io/current/connect/index.html">Kafka Connect</a> (which polls tables in the database and turns them into Avro-encoded messages), and <a href="https://debezium.io/">Debezium</a> (which tails the binary log of your database). Both are used pretty extensively, but they each have downsides. Kafka Connect has no way of sending deletions, since it polls the database, and deleted rows aren’t in the database any more. Debezium is heavily tied to your internal database schema (so is Kafka Connect by default, but you can write custom connectors to get around that).</p><p>So unfortunately, neither of these solutions gives you the whole picture without a bunch of pain points.</p><p>In an ideal world, your database schema is perfect! Everyone will want every column on your table and nothing in there is confusing in any way.</p><p>In the real world, you need your database schema to be <strong>internal </strong>and shielded from your consumers. You’re going to have implementation details that just aren’t relevant to anyone else. You may also want to combine multiple tables into a single event without having to write a separate joiner service downstream or being forced to write views for every table. You want to publish <strong>external-facing</strong> messages which use your data but <strong>not</strong> your schema.</p><p>That’s problem 1.</p><h4>The Transaction Gotcha</h4><p>We’ve been talking about sending your database state around — but let’s not forget that Kafka can and should still be used to send <strong>events</strong>. Most services that have state will still want to send events down the Kafka pipe. Keeping this in mind introduces one more sneaky issue: Transactions.</p><p>When writing data to a database, the write can fail (due to deadlocks, timeouts, etc.). Writes can also fail to Kafka (downtime, timeouts, broker issues). If one succeeds and not the other, you’ve now broken your guarantees of “single source of truth”.</p><p>Let’s say you’re writing your Character to a table, and sending a “Character Requested” event to a separate Kafka topic (perhaps with user and timestamp information). If you do this all in one transaction, the Character write can succeed but the sending the event can fail (meaning you know about the new character but the event didn’t go out), or the event can succeed but the database write can fail (meaning the event went out but it’s referencing a character that was never written).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*DaJYzhCj3AtPBu-gNP7qTw.png" /><figcaption>Write works to Kafka but not the database — Luke is in the topic but not the service’s own DB.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*9Fy84Z4Y_hMNod7pQinVVA.png" /><figcaption>Write works to the DB but not Kafka — downstream systems will not get the new write.</figcaption></figure><p>That’s problem 2.</p><p>So how do we do it? How do we marry our database and Kafka in a way that keeps our data <strong>eventually consistent</strong>, allows us to use all our lovely relational database tools for our web apps, provides the advantages of an Event-Driven Microservices architecture, and even lets us break up long-running monoliths?</p><p>Go forward and read <a href="https://medium.com/flippengineering/introducing-deimos-using-kafka-as-the-data-backbone-for-your-architecture-205bbc248391">Part 2</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8316ab7db5e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/using-kafka-as-a-data-backbone-part-1-8316ab7db5e0">Using Kafka as a Data Backbone: Part 1</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Engineer to Manager and Back Again]]></title>
            <link>https://medium.com/flippengineering/from-engineer-to-manager-and-back-again-64e796d45945?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/64e796d45945</guid>
            <category><![CDATA[career-paths]]></category>
            <category><![CDATA[management]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Flipp Engineering]]></dc:creator>
            <pubDate>Mon, 28 Oct 2019 19:58:11 GMT</pubDate>
            <atom:updated>2019-06-21T13:22:33.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*jWnZJwvGO7f3tCvC" /></figure><p><em>by Daniel Orner, Staff Engineer at Flipp</em></p><p><strong>“Some are born great, some achieve greatness, and some have greatness thrust upon ‘em.”</strong></p><p><strong>— Malvolio, <em>Twelfth Night II:5</em></strong></p><p><em>So what does the term “team lead” mean to you?</em></p><p>Many moons ago, I joined Flipp as a senior software engineer. At the time, Flipp was still a relatively raw startup, with under 40 employees. Coming from an enormous multinational conglomerate, where after five years I was still considered a “junior” employee, the title change was a nice surprise.</p><p>I found myself in a small team where I could make a huge difference. We were tasked with improving and adding features to “Fadmin”, the “flyer administration” system which our in-house operations team used. As time went on, I became more confident in my role and started mentoring other, more junior devs. I took part in more conversations with our stakeholders and liaised with other teams, as well as taking on coaching responsibilities. I did more design and architecture work. I tried to make sure we were iterating and improving our sprint and JIRA process. In early 2016, I got another pleasant surprise by having my job title automatically bumped up to “Team Lead, Software Engineering”.</p><p>This felt nice.</p><p>At the time, our team makeup was as follows:</p><ul><li>A team lead — me;</li><li>Four other devs and two QA developers (as they were called then — we now call them Software Engineers in Test);</li><li>A dedicated Product Owner</li><li>Contacts on our in-house Operations team who acted as stakeholders.</li></ul><p>The Product Owner was not only responsible for defining what we should be working on and prioritizing it, but was also in charge of “delivery”. I consider “delivery” to refer to ensuring that the team is working well, that there are no blockers with other teams, that there is no confusion with the requirements, that we do the things we say we’ll do, etc.</p><p>My own coach was a Director of Engineering, who was involved in both the technical and the “people” side of things and helped coach me through coaching, among other things.</p><p>This was my calendar in February 2016:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZFZMMkN7xu6FjdHi" /></figure><p>And here’s what it looked like later that year:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Y3ZiwfBP5lvXKUv" /></figure><p>Part of this was due to the fact that my team and its responsibilities were growing. We had started a brand-new project which was going to demand more of my time. Essentially we broke out a separate sub-team which I was also responsible for. Our company was also expanding rapidly in its size — probably <em>too</em> rapidly.</p><p>This trend continued for another year, at which point I was the “architect” for no less than four separate sub-teams, with almost 30 people in total. By late 2017, my schedule was almost entirely meetings and nothing else. This was despite the fact that my original team still did not have a senior dev on it. I was still responsible for making most of the technical choices and mentoring the junior devs. I was sad that I couldn’t give everyone my full attention, but still felt elated that so much responsibility was being trusted to me.</p><p>During this time, Flipp had been making an effort to better define its roles. Team Lead was a tricky one. They realized that the benefit of a Product Owner would be better realized by allowing them to take a step back and think bigger-picture and longer-term. The day-to-day duties which the Product Owner used to have were put on the Team Lead and/or a Scrum Master, depending on how many we had and which teams had them.</p><p>We also realized we had to get better at coaching and performance management. This became a focus of the Team Lead role as well. This was done without actively reducing the existing expectations of a Team Lead to be the “most senior engineer” on the team, and responsible for all the architecture and technical decisions as well.</p><p>Eventually, this definition broke.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*wV4mDsQtk7NgM6pG" /></figure><p>We realized that having a single person be responsible for so much simply wasn’t feasible. The Team Lead role transitioned from essentially being a technical lead role in 2016, to an “engineering manager” in 2018. The main focus of the role was now on “people” (performance management, coaching, and growth) and “delivery” (ensuring things weren’t blocked and were delivered on time). We introduced a new “Tech Lead” role which we slowly rolled out to other teams as a way to allow someone other than the team lead to focus on the architecture, design and implementation.</p><p>Like the proverbial frog in the kettle, the changes to the role definition happened so slowly that I didn’t quite realize what was going on until I started boiling.</p><p>The key event which made me realize that I was no longer what I wanted to be was a negative performance review. We had had a difficult term, and I was shocked to get my first “bad” rating, largely due to delivery issues. Part of this was due to confusion about my responsibilities, but that definitely wasn’t the full picture. I was wearing so many hats that my “team lead” hat, which was my primary role, started falling off.</p><p>“Shock” probably doesn’t quite cover the fullness of the reaction. Not only was I sad that I had messed up, I was also angry that I hadn’t seen it coming. It took me several days to be able to think about anything else.</p><p>Several weeks later, my coach and the VP of Engineering sat me down in a meeting and said to me that they’d realized they never actually gave me a choice about whether or not to be a Team Lead. They asked me the honest question: “Is this what you want to do?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-6U43yzpANMz6WEf" /></figure><p>I took the question hard, and entirely the wrong way. My response was, “Do you think I’m incapable of doing my job?” I was both scared that I was failing, and insulted that they’d think I was.</p><p>At Flipp, we have long had two tracks for career progression. The People track led from Senior Engineer to Team Lead to Director. The Technical track led from Senior Engineer to Staff Engineer to Principal Engineer. However, we had about three times as many Team Leads as Staff Engineers. The idea that Staff was just as achievable and just as important as Team Lead wasn’t something that had sunk in.</p><p>We had a lot of resources to help out with things like delivery and coaching. We’d done training seminars and changed our focus. I thought that with help, I probably could be a good Team Lead. But I thought back on the times when I really thought I was making a difference, and when I really enjoyed my work, and those times were not when I was doing performance management, one-on-ones, interviews, or (shudder) performance reviews. I simply couldn’t keep a birds-eye view on the team when I was also knee-deep in the weeds on the technical side.</p><p>After much soul-searching, I told my coach that I didn’t want to be a Team Lead any more.</p><p>This was a hard decision. There were (and are) a number of things I really enjoy about being a Team Lead. Being responsible for team culture and team health is something I think I was good at — we were a very close-knit group, and I felt my other devs looked up to me and appreciated me. I enjoyed being in meetings with other leadership people, being part of discussions that were basic to how the company functioned and helping to define roles and point to improvements that needed to happen around communication, compensation, policies, etc.</p><p>But the fact that I now realized that in order to be effective, I needed to spend <em>all</em> my time in this headspace and leave the technical side to others, made me realize that it simply wasn’t what I wanted to do.</p><p>I also had to admit that I was, you know, <em>bad</em> at something. Or at least not as good as I needed to be.</p><p>It took months to find a candidate willing to replace me as Team Lead. His leadership style was and is vastly different from my own. One of the first things I realized when my new team lead had established himself is that I had been running the team as my own fiefdom. As both the senior technical dev and the manager, I made all the decisions and, while (I hope) I listened to feedback, I had the final say in everything. Having to make myself accountable to others was something I found I hadn’t been used to doing and was an essential skill I began to put more effort into.</p><p>It was also really interesting to work <em>with</em> a team lead instead of <em>as</em> a team lead. Because of the way the role changed over the years, I’d never really had my own team lead at all. Working closely with one allowed me to see not only my shortcomings but also appreciate the things I’d done right and learned well during the role. I was able to both give useful feedback and understand why the decision I made was the right one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*JEMWSFJSFngiMBBa" /></figure><p>I also realized that many of the things I enjoyed didn’t go away. I still act as a mentor to others on my team and I am still part of conversations which help to define how we as a company think of ourselves. I spearheaded a Tech Lead (now Tech Head) group with other tech leads across the company to drive technical discussions and improvements, and this filled much of the void I was worried would open up as I slowly left the Team Lead space.</p><p>Do I regret being a Team Lead? Hell no. I learned an incredible amount in a few years which I’d never have gotten the chance to learn otherwise. Part of that was understanding which of those things appeal to me and which I’m more comfortable leaving behind.</p><p>In the end, what I found most important was to ask the question, “Do I enjoy what I’m doing? If so, why? If not, why?” We all must grow in our work, make mistakes, and learn from them. If you find work stressful because you’re not good enough at it yet, the answer there is to get resources and help until you are. But if it’s because the work doesn’t speak to you and isn’t where you want to spend your time, see what you can do to change that.</p><p>We work in a creative field, where we are incredibly fortunate to be able to feel fulfilled by what we do. We don’t do manual labour or even professional work like accountancy or law where it’s all about following the rules. We want to make a difference and in today’s market, we have the freedom to choose the kind of work that best fits our strengths and interests.</p><p>Go out there and be you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e796d45945" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/from-engineer-to-manager-and-back-again-64e796d45945">From Engineer to Manager and Back Again</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Delivery Using Vertical Engineering Teams — Part 3: Coding Challenges]]></title>
            <link>https://medium.com/flippengineering/scaling-delivery-using-vertical-engineering-teams-part-3-coding-challenges-52d74da00216?source=rss----2562f761b615---4</link>
            <guid isPermaLink="false">https://medium.com/p/52d74da00216</guid>
            <category><![CDATA[flipp-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[engineering-organization]]></category>
            <dc:creator><![CDATA[Flipp Engineering]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 21:01:02 GMT</pubDate>
            <atom:updated>2019-02-28T21:01:02.400Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Scaling Delivery Using Vertical Engineering Teams — Part 3: Coding Challenges</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NCulRO7tMrF5WwSXAR8fA.jpeg" /></figure><p>By: Brendan Cone, Director of Engineering, Flipp</p><p><em>This is the third part in a series of articles discussing Flipp’s migration of its engineering organization from system-based teams to vertical (or “mission-based”) teams, and the challenges we experienced along the way. This was written last year from my perspective as the team lead of one of the first teams to make the jump a couple of years prior.</em></p><p><em>In </em><a href="https://medium.com/flippengineering/scaling-delivery-using-vertical-engineering-teams-part-1-human-challenges-964ea1aae3a7"><em>Part 1</em></a><em> and </em><a href="https://medium.com/flippengineering/scaling-delivery-using-vertical-engineering-teams-part-2-process-challenges-3451048d3c36"><em>Part 2</em></a><em>, I talked through the challenges of people growth and challenges of work coordination. In Part 3, I will walk through some of the challenges we had more specifically around how we coded, and describe how we chose to address them.</em></p><h3>Part 3: Coding Challenges</h3><h3>When each vertical team has complete freedom to solve problems in the way they choose, technology sprawl is inevitable.</h3><p>We decided, as a team, that the best language to work with for a major back-end project several months back was going to be Typescript. We concluded that a serverless architecture made the most sense for the problem set. As a company, we had never used many of the technologies that we ended up using on that project in any production capacity.</p><p>We had the freedom to do this due to the nature of our team. It ended up being fruitful in that we are leveraging many of the features of the language and the infrastructure, but as an engineering organization it left us with a problem. We were the only team that had worked with that specific combination of technologies and coding paradigms.</p><h3>Solution: Platformization and standardization.</h3><p>As developers and as human beings, we tend towards the path of least resistance. As a deadline looms in the distance, we are resourceful; we will cut scope where we can to get something out on time. The challenge, then, as an organization, is to ensure that the path of least resistance also happens to be the best path for the company as a whole.</p><p>At Flipp, we have invested countless hours into developing a microservice platform as well as a set of boilerplates for our most common programming languages, frameworks and tech stacks. The platform takes care of many of the infrastructure challenges that the average developer shouldn’t have to worry about such as load balancing, containerization, continuous delivery and continuous integration. The boilerplates make several opinionated choices on individual packages that influence developers towards consistency and help define a base structure for the applications we produce.</p><p>While teams still have the freedom to deviate from the standard if their particular problem set suits it, they are encouraged to develop new boilerplates when they do. Our team produced a boilerplate for our serverless typescript architecture so that if another team finds that this is the best architecture for them, many of the technical challenges that we had to solve are already solved for them.</p><p>As a close deadline looms, developers will often find that the best course of action is to use one of the boilerplates that have been developed by the Flipp engineering community to save the manpower costs of attempting to solve all of these problems again from scratch. This allows the organization to drive toward a smaller set of standards.</p><h3>Each vertical team ends up reinventing the wheel.</h3><p>When you have everybody you need on your team to develop a feature front-to-back, it can be enticing to do just that. But what happens when another vertical team comes along and has to solve the exact same problem? How do we let them know that we think we already have a pretty good solution?</p><h3>Solution: Make opinionated choices and tell people about them.</h3><p>In addition to the boilerplates mentioned above, Flipp has also invested time in developing custom modules and packages for our most common languages which solve problems in a standardized fashion. From standardized logging formats and methods, to business metric monitoring and alerting, to reporting and exporting functionality, we have covered many of the major problem sets we have experienced repeatedly in the past. We make consistent improvements to these modules in order to benefit all the systems that use them.</p><p>The next challenge that logically follows is one of dissemination: how do all of the other vertical teams find out about these new things that are being developed for their use?</p><p>As our company’s arsenal of boilerplates, modules and packages is built up, we continue to have regular meetings among our technical leads where we discuss pain points and agree on common ways to solve them. By virtue of having the technical leads participate in the solution, it is our hope that every team has these standardization efforts top-of-mind when developing a new service or feature.</p><p>As well, the case for their use is simple when you present it as the path of least resistance: a complex task that would take weeks or months can be reduced to the simpler task of linking together several services which already exist developed by the company at large, with only a bare minimum of added business logic.</p><h3>Conclusion</h3><p>The transition from system teams to vertical teams can be foreign and uncomfortable for the team members involved. We encountered quite a few challenges, and we recognize and understand that there will be many more to come as we continue to make the transition.</p><p>However, with all this being said, the benefits have certainly outweighed the costs. The small adjustments that we have made as a company to attack these problems have allowed us to make the transition successfully and move into a much more promising future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52d74da00216" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flippengineering/scaling-delivery-using-vertical-engineering-teams-part-3-coding-challenges-52d74da00216">Scaling Delivery Using Vertical Engineering Teams — Part 3: Coding Challenges</a> was originally published in <a href="https://medium.com/flippengineering">Flipp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>