Distributed Systems, Kafka, Scala

Kafka Schema Registry

This is the 3rd post in a small mini series that I will be doing using Apache Kafka + Avro. The programming language will be Scala. As such the following prerequisites need to be obtained should you wish to run the code that goes along with each post. The other point is that I am mainly a Windows user, as such the instructions, scripts will have a Windows bias to them. So if you are not a Windows user you will need to find the instructions for your OS of choice.

 

Prerequisites

So go and grab that lot if you want to follow along.

 

Last time we talked about how to create a Kafka Producer/Consumer which uses the KafkaAvroSerializer when using Avro data of a specific type. We also used the Kafka Schema Registry and had a tiny introduction as to what the Kafka Schema Registry was all about. This time we will be looking at the Kafka Schema Registry in a lot more detail.

 

 

Where is the code for this post?

You can grab the code that goes with this post from here : https://github.com/sachabarber/KafkaAvroExamples/tree/master/KafkaSpecificAvroBrokenProducer and here too : https://github.com/sachabarber/KafkaAvroExamples/tree/master/KafkaSchemaRegistryTests

 

Kafka Schema Registry Deep Dive

The idea behind the Schema Registry is that Confluent provide it as a service that exposes a REST API that integrates closely with the rest of the Kafka stack. The Schema Registry acts as a single store for schema metadata, in a versioned historical manner. It also provides compatibility settings that allow the evolution of schemas according to the configured compatibility setting. As we have already seen in the last post there are also serializers that are provided that work with the Registry and Avro format. Thus far we have only seen a Producer/Consumer both of which use the KafkaAvroSerializer, but there is also a Serde (serializer/deserializer) available when working with Kafka Streams.Which we will talk about in the next post.

 

You may be wondering just why you may want to use some sort of schema registry. Well have you ever found yourself in a situation where you store a JSON blob in a row in a database, and then later you make changes to the format of the original object that was used to store these historic rows. Then you find yourself in the unenviable position of no longer being able to easily deserialize your old database JSON data. You need to either write some mapping code or evolve the data to the latest schema format. This is not an easy task, I have done this by hand once or twice and its hard to get right. This is the job of the Kafka Schema registry essentially. It’s a helping/guiding light to help you traverse this issue.

 

I have taken the next section from the official docs, as there is good detail in here that is important to the rest of this post, and it really is a case of the official docs saying it best, so let’s just borrow this bit of text, the rest of the post will put this into action

 

The Schema Registry is a distributed storage layer for Avro Schemas which uses Kafka as its underlying storage mechanism. Some key design decisions:

  • Assigns globally unique id to each registered schema. Allocated ids are guaranteed to be monotonically increasing but not necessarily consecutive.
  • Kafka provides the durable backend, and functions as a write-ahead changelog for the state of the Schema Registry and the schemas it contains.
  • The Schema Registry is designed to be distributed, with single-master architecture, and ZooKeeper/Kafka coordinates master election (based on the configuration).

 

Kafka Backend

Kafka is used as the Schema Registry storage backend. The special Kafka topic <kafkastore.topic> (default _schemas), with a single partition, is used as a highly available write ahead log. All schemas, subject/version and id metadata, and compatibility settings are appended as messages to this log. A Schema Registry instance therefore both produces and consumes messages under the _schemas topic. It produces messages to the log when, for example, new schemas are registered under a subject, or when updates to compatibility settings are registered. The Schema Registry consumes from the _schemas log in a background thread, and updates its local caches on consumption of each new _schemas message to reflect the newly added schema or compatibility setting. Updating local state from the Kafka log in this manner ensures durability, ordering, and easy recoverability.

 

Compatibility

The Schema Registry server can enforce certain compatibility rules when new schemas are registered in a subject. Currently, we support the following compatibility rules.

  • Backward compatibility (default): A new schema is backwards compatible if it can be used to read the data written in the latest (older) registered schema.
  • Transitive backward compatibility: A new schema is transitively backwards compatible if it can be used to read the data written in all previously registered schemas. Backward compatibility is useful for loading data into systems like Hadoop since one can always query data of all versions using the latest schema.
  • Forward compatibility: A new schema is forward compatible if the latest (old) registered schema can read data written in this schema, or to put this another way “data encoded with a newer schema can be read with an older schema.”
  • Transitive forward compatibility: A new schema is transitively forward compatible if all previous schemas can read data written in this schema. Forward compatibility is useful for consumer applications that can only deal with data in a particular version that may not always be the latest version.
  • Full compatibility: A new schema is fully compatible if it’s both backward and forward compatible with the latest registered schema.
  • Transitive full compatibility: A new schema is transitively full compatible if it’s both backward and forward compatible with all previously registered schemas.
  • No compatibility: A new schema can be any schema as long as it’s a valid Avro.

 

An Evolution Example

Say we had this initial schema

{"namespace": "barbers.avro",
 "type": "record",
 "name": "person",
 "fields": [
     {"name": "name", "type": "string"},
     {"name": "age",  "type": "int"},
 ]
}

We can evolve this schema into this one, where we supply a default location.

{"namespace": "barbers.avro",
 "type": "record",
 "name": "person",
 "fields": [
     {"name": "name", "type": "string"},
     {"name": "age",  "type": "int"},
	 {"name": "location", "type": "string", "default": "uk"}
 ]
}

 

This allows data encoded with the old one to be read using this new schema. This is backward compatible. If we had not of supplied this default for ”location” this would no longer be backward compatible.

 

Forward compatibility means that data encoded with a newer schema can be read with an older schema. This new schema is also forward compatible with the original schema, since we can just drop the defaulted new field “location” when projecting new data into the old. Had the new schema chosen to no longer include “age” column it would not be forward compatible, as we would not know how to fill in this field for the the old schema.

For more information on this you should have a bit more of a read here : https://docs.confluent.io/current/avro.html

 

Ok so I think that gives us a flavor of what the Schema Registry is all about, let’s carry on and see some code examples.

 

So how do I run this stuff?

 

As I stated above you will need to download a few things, but once you have those in place you may find the small PowerShell script useful that is inside the projects called “RunThePipeline.ps1”. This script does a few things, such as cleans the Kafka/Zookeeper logs, stops any previous instances, starts new instances and also creates the Kafka topic (which you must have before you can use the code).

IMPORTANT NOTE : I have altered the Kafka log paths, and where Zookeeper logs to. This can be done using the relevant properties files from the Confluent installation

 

image

 

server.properties

This line was changed

# A comma seperated list of directories under which to store log files
log.dirs=c:/temp/kafka-logs

 

zookeeper.properties

This line was changed

# the directory where the snapshot is stored.
dataDir=c:/temp/zookeeper

 

The PowerShell script will be making assumptions based on the where you changed these values to, so if you have different settings for these please edit the PowerShell script too )

 

Essentially you need to have the following running before you can run the code example (this is what the PowerShell script automates for you, though you may prefer to use the Confluent CLI, I just had this script from a previous project, and it also cleans out old data which is useful when you are experimenting, and it also creates the required topic)

 

  • Zookeeper
  • Kafka broker
  • Starts the Schema Registry
  • Kafka topic created

 

 

Using the producer to test out the Registry

This is this project in the GitHub demo code : https://github.com/sachabarber/KafkaAvroExamples/tree/master/KafkaSpecificAvroBrokenProducer

 

Since we worked with the Schema Registry and a Kafka Producer that made use of the Registry in the last post, I thought it might a good idea to make some changes to the publisher of the last post, to see if we can create some compatibility tests against the Schema Registry that the Producer is using.

 

So so before we see the running code, lets examine some schemas that are run in the PublisherApp in this exact order

 

User schema

{
    "namespace": "com.barber.kafka.avro",
     "type": "record",
     "name": "User",
     "fields":[
         {
            "name": "id", "type": "int"
         },
         {
            "name": "name",  "type": "string"
         }
     ]
}

 

User without name schema

{
    "namespace": "com.barber.kafka.avro",
     "type": "record",
     "name": "User",
     "fields":[
         {
            "name": "id", "type": "int"
         }
     ]
}

 

User with boolean “Id” field schema

{
    "namespace": "com.barber.kafka.avro",
     "type": "record",
     "name": "User",
     "fields":[
         {
            "name": "id", "type": "boolean"
         }
     ]
}

 

Another completely new type with string “Id” field schema

{
    "namespace": "com.barber.kafka.avro",
     "type": "record",
     "name": "AnotherExampleWithStringId",
     "fields":[
         {
            "name": "id", "type": "string"
         }
     ]
}

 

So since the Kafka Producer is setup to use the Kafka Schema Registry and is sending Avro using the KafkaAvroSerializer for the key, we start with the 1st schema (User Schema) shown above being the one that is registered against the Kafka Schema Registry subject Kafka-value (we will see more of the Registry API below for now just understand that when using the Schema Registry a auto registration is done against the topic/value for the given producer, on the 1st one to use the topic being the one that sets these items for the Registry).

 

Ok so we have stated that we start out with the 1st schema (User Schema) shown above, and then we progress through each of the other schemas shown above and try and send the Avro serialized data across the Kafka topic, here is the code from the Producer App

package com.barber.kafka.avro

import java.util.{Properties, UUID}

import io.confluent.kafka.serializers.KafkaAvroSerializer
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import org.apache.kafka.common.serialization.StringSerializer

class KafkaDemoAvroPublisher(val topic:String) {

  private val props = new Properties()
  props.put("bootstrap.servers", "localhost:9092")
  props.put("schema.registry.url", "http://localhost:8081")
  props.put("key.serializer", classOf[StringSerializer].getCanonicalName)
  props.put("value.serializer",classOf[KafkaAvroSerializer].getCanonicalName)
  props.put("client.id", UUID.randomUUID().toString())

  private val producer =   new KafkaProducer[String,User](props)
  private val producerUserWithoutName =   new KafkaProducer[String,UserWithoutName](props)
  private val producerUserWithBooleanIdBad =   new KafkaProducer[String,UserWithBooleanId](props)
  private val producerAnotherExampleWithStringIdBad = new KafkaProducer[String,AnotherExampleWithStringId](props)

  def send(): Unit = {
    try {
      val rand =  new scala.util.Random(44343)

      //we expect this to work, as its the one that is going to define the Avro format of then topic
      //since its the 1st published message on the topic (Assuming you have not preregistered the topic key + Avro schemea
      //with the schema registry already)
      for(i <- 1 to 10) {
        val id = rand.nextInt()
        val itemToSend = User(id , "ishot.com")
        println(s"Producer sending data ${itemToSend.toString}")
        producer.send(new ProducerRecord[String, User](topic, itemToSend))
        producer.flush()
      }


      //we expect this to work as having a User without a name is ok, as Name is a "string" so can be empty
      for(i <- 1 to 10) {
        val id = rand.nextInt()
        val itemToSend = UserWithoutName(id)
        println(s"Producer sending data ${itemToSend.toString}")
        producerUserWithoutName.send(new ProducerRecord[String, UserWithoutName](topic, itemToSend))
        producerUserWithoutName.flush()
      }


      //we expect this to fail as its trying to send a different incompatible Avro object on the topic
      //which is currently using the "User" (Avro object / Schema)
      sendBadProducerValue("UserWithBooleanId", () => {
        val itemToSend = UserWithBooleanId(true)
        println(s"Producer sending data ${itemToSend.toString}")
        producerUserWithBooleanIdBad.send(new ProducerRecord[String, UserWithBooleanId](topic, itemToSend))
        producerUserWithBooleanIdBad.flush()
      })

      //we expect this to fail as its trying to send a different incompatible Avro object on the topic
      //which is currently using the "User" (Avro object / Schema)
      sendBadProducerValue("AnotherExampleWithStringId", () => {
        val itemToSend = AnotherExampleWithStringId("fdfdfdsdsfs")
        println(s"Producer sending data ${itemToSend.toString}")
        producerAnotherExampleWithStringIdBad.send(new ProducerRecord[String, AnotherExampleWithStringId](topic, itemToSend))
        producerAnotherExampleWithStringIdBad.flush()
      })

    } catch {
      case ex: Exception =>
        println(ex.printStackTrace().toString)
        ex.printStackTrace()
    }
  }

  def sendBadProducerValue(itemType: String, produceCallback: () => Unit) : Unit = {
    try {
      //we expect this to fail as its trying to send a different incompatible
      // Avro object on the topic which is currently using the "User" (Avro object / Schema)
      println(s"Sending $itemType")
      produceCallback()
    } catch {
      case ex: Exception => {
        println("==============================================================================\r\n")
        println(s" We were expecting this due to incompatble '$itemType' item being sent\r\n")
        println("==============================================================================\r\n")
        println(ex.printStackTrace().toString)
        println()
        ex.printStackTrace()
      }
    }
  }
}

 

Now lets see the relevant output

 

NOTE : This assumes a clean run with a new empty topic

 

 

We start by sending some User Schema data, which is fine as it’s the first data on the topic

 

Producer sending data {“id”: -777306865, “name”: “ishot.com”}
06:47:05.816 [kafka-producer-network-thread | 6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] DEBUG org.apache.kafka.clients.NetworkClient – [Producer clientId=6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] Using older server API v3 to send PRODUCE {acks=1,timeout=30000,partitionSizes=[avro-specific-demo-topic-0=88]} with correlation id 8 to node 0
Producer sending data {“id”: 1227013473, “name”: “ishot.com”}
06:47:05.818 [kafka-producer-network-thread | 6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] DEBUG org.apache.kafka.clients.NetworkClient – [Producer clientId=6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] Using older server API v3 to send PRODUCE {acks=1,timeout=30000,partitionSizes=[avro-specific-demo-topic-0=88]} with correlation id 9 to node 0
Producer sending data {“id”: 1899269599, “name”: “ishot.com”}
06:47:05.821 [kafka-producer-network-thread | 6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] DEBUG org.apache.kafka.clients.NetworkClient – [Producer clientId=6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] Using older server API v3 to send PRODUCE {acks=1,timeout=30000,partitionSizes=[avro-specific-demo-topic-0=88]} with correlation id 10 to node 0
Producer sending data {“id”: -1764893671, “name”: “ishot.com”}

 

We then try send some User Without Name Schema data, which is fine as it’s compatible with the User Schema already registered in the Kafka Registry

 

Producer sending data {“id”: -1005363706}
06:47:05.895 [kafka-producer-network-thread | 6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] DEBUG org.apache.kafka.clients.NetworkClient – [Producer clientId=6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] Using older server API v3 to send PRODUCE {acks=1,timeout=30000,partitionSizes=[avro-specific-demo-topic-0=78]} with correlation id 4 to node 0
Producer sending data {“id”: -528430870}
06:47:05.900 [kafka-producer-network-thread | 6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] DEBUG org.apache.kafka.clients.NetworkClient – [Producer clientId=6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] Using older server API v3 to send PRODUCE {acks=1,timeout=30000,partitionSizes=[avro-specific-demo-topic-0=78]} with correlation id 5 to node 0
Producer sending data {“id”: -877322591}
06:47:05.905 [kafka-producer-network-thread | 6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] DEBUG org.apache.kafka.clients.NetworkClient – [Producer clientId=6c9d7365-1216-4c4e-9cfe-da3e3d5654d1] Using older server API v3 to send PRODUCE {acks=1,timeout=30000,partitionSizes=[avro-specific-demo-topic-0=78]} with correlation id 6 to node 0
Producer sending data {“id”: 2048308094}

 

We then try send some User With Boolean Id Field Schema data, which we expect to be NOT acceptable/incompatible with the User Schema already registered in the Kafka Registry. This is due to the fact we have changed the Id field into a boolean, where the already registered User Schema expects this field to be an “int”. So does it fail?

 

In a word yes, here is the relevant output

 

Sending UserWithBooleanId
Producer sending data {“id”: true}

06:47:05.954 [main] DEBUG io.confluent.kafka.schemaregistry.client.rest.RestService – Sending POST with input {“schema”:”{\”type\”:\”record\”,\”name\”:\”User\”,\”namespace\”:\”com.barber.kafka.avro\”,\”fields\”:[{\”name\”:\”id\”,\”type\”:\”boolean\”}]}”} to http://localhost:8081/subjects/avro-specific-demo-topic-value/versions
==============================================================================

We were expecting this due to incompatble ‘UserWithBooleanId’ item being sent

==============================================================================

org.apache.kafka.common.errors.SerializationException: Error registering Avro schema: {“type”:”record”,”name”:”User”,”namespace”:”com.barber.kafka.avro”,”fields”:[{“name”:”id”,”type”:”boolean”}]}
Caused by: io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException: Schema being registered is incompatible with an earlier schema; error code: 409
    at io.confluent.kafka.schemaregistry.client.rest.RestService.sendHttpRequest(RestService.java:170)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.httpRequest(RestService.java:188)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:245)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:237)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:232)
    at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.registerAndGetId(CachedSchemaRegistryClient.java:59)
    at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.register(CachedSchemaRegistryClient.java:91)
    at io.confluent.kafka.serializers.AbstractKafkaAvroSerializer.serializeImpl(AbstractKafkaAvroSerializer.java:72)
    at io.confluent.kafka.serializers.KafkaAvroSerializer.serialize(KafkaAvroSerializer.java:54)
    at org.apache.kafka.common.serialization.ExtendedSerializer$Wrapper.serialize(ExtendedSerializer.java:65)
    at org.apache.kafka.common.serialization.ExtendedSerializer$Wrapper.serialize(ExtendedSerializer.java:55)
    at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:807)
    at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:784)
    at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:671)
    at com.barber.kafka.avro.KafkaDemoAvroPublisher.$anonfun$send$3(KafkaDemoAvroPublisher.scala:54)
    at com.barber.kafka.avro.KafkaDemoAvroPublisher$$Lambda$17/746074699.apply$mcV$sp(Unknown Source)
    at com.barber.kafka.avro.KafkaDemoAvroPublisher.sendBadProducerValue(KafkaDemoAvroPublisher.scala:79)
    at com.barber.kafka.avro.KafkaDemoAvroPublisher.send(KafkaDemoAvroPublisher.scala:51)
    at com.barber.kafka.avro.PublisherApp$.delayedEndpoint$com$barber$kafka$avro$PublisherApp$1(PublisherApp.scala:6)
    at com.barber.kafka.avro.PublisherApp$delayedInit$body.apply(PublisherApp.scala:3)
    at scala.Function0.apply$mcV$sp(Function0.scala:34)
    at scala.Function0.apply$mcV$sp$(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App.$anonfun$main$1$adapted(App.scala:76)
    at scala.App$$Lambda$5/511833308.apply(Unknown Source)
    at scala.collection.immutable.List.foreach(List.scala:378)
    at scala.App.main(App.scala:76)
    at scala.App.main$(App.scala:74)
    at com.barber.kafka.avro.PublisherApp$.main(PublisherApp.scala:3)
    at com.barber.kafka.avro.PublisherApp.main(PublisherApp.scala)
o

 

 

We then try send some Completely Different Object With String Id Field Schema data, which we expect to be NOT acceptable/incompatible with the User Schema already registered in the Kafka Registry. This is due to the fact we have changed the Id field into a string, where the already registered User Schema expects this field to be an “int”, and we have also omitted a required “name” field in this new type.

So does it fail?

 

In a word yes, here is the relevant output

 

Sending AnotherExampleWithStringId
Producer sending data {“id”: “fdfdfdsdsfs”}

06:47:06.059 [main] DEBUG io.confluent.kafka.schemaregistry.client.rest.RestService – Sending POST with input {“schema”:”{\”type\”:\”record\”,\”name\”:\”AnotherExampleWithStringId\”,\”namespace\”:\”com.barber.kafka.avro\”,\”fields\”:[{\”name\”:\”id\”,\”type\”:\”string\”}]}”} to http://localhost:8081/subjects/avro-specific-demo-topic-value/versions
==============================================================================

We were expecting this due to incompatble ‘AnotherExampleWithStringId’ item being sent

==============================================================================

()

org.apache.kafka.common.errors.SerializationException: Error registering Avro schema: {“type”:”record”,”name”:”AnotherExampleWithStringId”,”namespace”:”com.barber.kafka.avro”,”fields”:[{“name”:”id”,”type”:”string”}]}
Caused by: io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException: Schema being registered is incompatible with an earlier schema; error code: 409
    at io.confluent.kafka.schemaregistry.client.rest.RestService.sendHttpRequest(RestService.java:170)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.httpRequest(RestService.java:188)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:245)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:237)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:232)
    at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.registerAndGetId(CachedSchemaRegistryClient.java:59)
    at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.register(CachedSchemaRegistryClient.java:91)
    at io.confluent.kafka.serializers.AbstractKafkaAvroSerializer.serializeImpl(AbstractKafkaAvroSerializer.java:72)
    at io.confluent.kafka.serializers.KafkaAvroSerializer.serialize(KafkaAvroSerializer.java:54)
    at org.apache.kafka.common.serialization.ExtendedSerializer$Wrapper.serialize(ExtendedSerializer.java:65)
    at org.apache.kafka.common.serialization.ExtendedSerializer$Wrapper.serialize(ExtendedSerializer.java:55)
    at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:807)
    at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:784)
    at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:671)
    at com.barber.kafka.avro.KafkaDemoAvroPublisher.$anonfun$send$4(KafkaDemoAvroPublisher.scala:63)
    at com.barber.kafka.avro.KafkaDemoAvroPublisher$$Lambda$18/871790326.apply$mcV$sp(Unknown Source)
    at com.barber.kafka.avro.KafkaDemoAvroPublisher.sendBadProducerValue(KafkaDemoAvroPublisher.scala:79)
    at com.barber.kafka.avro.KafkaDemoAvroPublisher.send(KafkaDemoAvroPublisher.scala:60)
    at com.barber.kafka.avro.PublisherApp$.delayedEndpoint$com$barber$kafka$avro$PublisherApp$1(PublisherApp.scala:6)
    at com.barber.kafka.avro.PublisherApp$delayedInit$body.apply(PublisherApp.scala:3)
    at scala.Function0.apply$mcV$sp(Function0.scala:34)
    at scala.Function0.apply$mcV$sp$(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App.$anonfun$main$1$adapted(App.scala:76)
    at scala.App$$Lambda$5/511833308.apply(Unknown Source)
    at scala.collection.immutable.List.foreach(List.scala:378)
    at scala.App.main(App.scala:76)
    at scala.App.main$(App.scala:74)
    at com.barber.kafka.avro.PublisherApp$.main(PublisherApp.scala:3)
    at com.barber.kafka.avro.PublisherApp.main(PublisherApp.scala)

Ok so that gives us a glimpse of what it’s like to work with the Kafka Producer and the Schema Registry. But surely there is more we can do with the Schema Registry REST API that is mentioned above?

 

Well yeah there is, we will now look at a second example in the codebase which will try a few more Schema Registry REST API calls.

 

 

 

 

Understanding Registry API

 

This is this project in the GitHub demo code : https://github.com/sachabarber/KafkaAvroExamples/tree/master/KafkaSchemaRegistryTests

 

I have chosen to use Akka Http for the REST API calls.

 

These are the 3 resources used by the code

 

compatibilityBACKWARD.json

{"compatibility": "BACKWARD"}

 

compatibilityNONE.json

{"compatibility": "NONE"}

 

simpleStringSchema.avsc

{"schema": "{\"type\": \"string\"}"}

 

 

Here is the entire codebase for various operations against the Schema Registry

import scala.io.Source
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import scala.concurrent._
import scala.concurrent.duration._
import akka.http.scaladsl.model._
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import scala.concurrent.Future
import scala.util.{Failure, Success}
import akka.http.scaladsl.unmarshalling.Unmarshal
import AkkaHttpImplicits.{executionContext, materializer, system}

object RegistryApp extends App {

  var payload = ""
  var result = ""
  val schemaRegistryMediaType = MediaType.custom("application/vnd.schemaregistry.v1+json",false)
  implicit  val c1 = ContentType(schemaRegistryMediaType, () => HttpCharsets.`UTF-8`)

  //These queries are the same ones found here, but instead of using curl I am using Akka Http
  //https://docs.confluent.io/current/schema-registry/docs/intro.html


  //  # Register a new version of a schema under the subject "Kafka-key"
  //  $ curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  //  --data '{"schema": "{\"type\": \"string\"}"}' \
  //  http://localhost:8081/subjects/Kafka-key/versions
  //  {"id":1}
  payload = Source.fromURL(getClass.getResource("/simpleStringSchema.avsc")).mkString
  result = post(payload,"http://localhost:8081/subjects/Kafka-key/versions")
  println("Register a new version of a schema under the subject \"Kafka-key\"")
  println("EXPECTING {\"id\":1}")
  println(s"GOT ${result}\r\n")


  //  # Register a new version of a schema under the subject "Kafka-value"
  //  $ curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  //  --data '{"schema": "{\"type\": \"string\"}"}' \
  //  http://localhost:8081/subjects/Kafka-value/versions
  //  {"id":1}
  payload = Source.fromURL(getClass.getResource("/simpleStringSchema.avsc")).mkString
  result = post(payload,"http://localhost:8081/subjects/Kafka-value/versions")
  println("Register a new version of a schema under the subject \"Kafka-value\"")
  println("EXPECTING {\"id\":1}")
  println(s"GOT ${result}\r\n")


  //  # List all subjects
  //  $ curl -X GET http://localhost:8081/subjects
  //    ["Kafka-value","Kafka-key"]
  result = get("http://localhost:8081/subjects")
  println("List all subjects")
  println("EXPECTING [\"Kafka-value\",\"Kafka-key\"]")
  println(s"GOT ${result}\r\n")


  //  # Fetch a schema by globally unique id 1
  //  $ curl -X GET http://localhost:8081/schemas/ids/1
  //  {"schema":"\"string\""}
  result = get("http://localhost:8081/schemas/ids/1")
  println("Fetch a schema by globally unique id 1")
  println("EXPECTING {\"schema\":\"\\\"string\\\"\"}")
  println(s"GOT ${result}\r\n")


  //  # List all schema versions registered under the subject "Kafka-value"
  //  $ curl -X GET http://localhost:8081/subjects/Kafka-value/versions
  //    [1]
  result = get("http://localhost:8081/subjects/Kafka-value/versions")
  println("List all schema versions registered under the subject \"Kafka-value\"")
  println("EXPECTING [1]")
  println(s"GOT ${result}\r\n")


  //  # Fetch version 1 of the schema registered under subject "Kafka-value"
  //  $ curl -X GET http://localhost:8081/subjects/Kafka-value/versions/1
  //  {"subject":"Kafka-value","version":1,"id":1,"schema":"\"string\""}
  result = get("http://localhost:8081/subjects/Kafka-value/versions/1")
  println("Fetch version 1 of the schema registered under subject \"Kafka-value\"")
  println("EXPECTING {\"subject\":\"Kafka-value\",\"version\":1,\"id\":1,\"schema\":\"\\\"string\\\"\"}")
  println(s"GOT ${result}\r\n")


  //  # Deletes version 1 of the schema registered under subject "Kafka-value"
  //  $ curl -X DELETE http://localhost:8081/subjects/Kafka-value/versions/1
  //  1
  result = delete("http://localhost:8081/subjects/Kafka-value/versions/1")
  println("Deletes version 1 of the schema registered under subject \"Kafka-value\"")
  println("EXPECTING 1")
  println(s"GOT ${result}\r\n")


  //  # Register the same schema under the subject "Kafka-value"
  //  $ curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  //  --data '{"schema": "{\"type\": \"string\"}"}' \
  //  http://localhost:8081/subjects/Kafka-value/versions
  //  {"id":1}
  payload = Source.fromURL(getClass.getResource("/simpleStringSchema.avsc")).mkString
  result = post(payload,"http://localhost:8081/subjects/Kafka-value/versions")
  println("Register the same schema under the subject \"Kafka-value\"")
  println("EXPECTING {\"id\":1}")
  println(s"GOT ${result}\r\n")


  //  # Deletes the most recently registered schema under subject "Kafka-value"
  //  $ curl -X DELETE http://localhost:8081/subjects/Kafka-value/versions/latest
  //  2
  result = delete("http://localhost:8081/subjects/Kafka-value/versions/latest")
  println("Deletes the most recently registered schema under subject \"Kafka-value\"")
  println("EXPECTING 2")
  println(s"GOT ${result}\r\n")


  //  # Register the same schema under the subject "Kafka-value"
  //  $ curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  //  --data '{"schema": "{\"type\": \"string\"}"}' \
  //  http://localhost:8081/subjects/Kafka-value/versions
  //  {"id":1}
  payload = Source.fromURL(getClass.getResource("/simpleStringSchema.avsc")).mkString
  result = post(payload,"http://localhost:8081/subjects/Kafka-value/versions")
  println("Register the same schema under the subject \"Kafka-value\"")
  println("EXPECTING {\"id\":1}")
  println(s"GOT ${result}\r\n")


  //  # Fetch the schema again by globally unique id 1
  //  $ curl -X GET http://localhost:8081/schemas/ids/1
  //  {"schema":"\"string\""}
  result = get("http://localhost:8081/schemas/ids/1")
  println("Fetch the schema again by globally unique id 1")
  println("EXPECTING {\"schema\":\"\\\"string\\\"\"}")
  println(s"GOT ${result}\r\n")


  //  # Check whether a schema has been registered under subject "Kafka-key"
  //  $ curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  //  --data '{"schema": "{\"type\": \"string\"}"}' \
  //  http://localhost:8081/subjects/Kafka-key
  //  {"subject":"Kafka-key","version":1,"id":1,"schema":"\"string\""}
  payload = Source.fromURL(getClass.getResource("/simpleStringSchema.avsc")).mkString
  result = post(payload,"http://localhost:8081/subjects/Kafka-key")
  println("Check whether a schema has been registered under subject \"Kafka-key\"")
  println("EXPECTING {\"subject\":\"Kafka-key\",\"version\":1,\"id\":1,\"schema\":\"\\\"string\\\"\"}")
  println(s"GOT ${result}\r\n")


  //  # Test compatibility of a schema with the latest schema under subject "Kafka-value"
  //  $ curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  //  --data '{"schema": "{\"type\": \"string\"}"}' \
  //  http://localhost:8081/compatibility/subjects/Kafka-value/versions/latest
  //  {"is_compatible":true}
  payload = Source.fromURL(getClass.getResource("/simpleStringSchema.avsc")).mkString
  result = post(payload,"http://localhost:8081/compatibility/subjects/Kafka-value/versions/latest")
  println("Test compatibility of a schema with the latest schema under subject \"Kafka-value\"")
  println("EXPECTING {\"is_compatible\":true}")
  println(s"GOT ${result}\r\n")


  //  # Get top level config
  //    $ curl -X GET http://localhost:8081/config
  //    {"compatibilityLevel":"BACKWARD"}
  result = get("http://localhost:8081/config")
  println("Get top level config")
  println("EXPECTING {\"compatibilityLevel\":\"BACKWARD\"}")
  println(s"GOT ${result}\r\n")


  //  # Update compatibility requirements globally
  //    $ curl -X PUT -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  //  --data '{"compatibility": "NONE"}' \
  //  http://localhost:8081/config
  //    {"compatibility":"NONE"}
  payload = Source.fromURL(getClass.getResource("/compatibilityNONE.json")).mkString
  result = put(payload,"http://localhost:8081/config")
  println("Update compatibility requirements globally")
  println("EXPECTING {\"compatibility\":\"NONE\"}")
  println(s"GOT ${result}\r\n")


  //  # Update compatibility requirements under the subject "Kafka-value"
  //  $ curl -X PUT -H "Content-Type: application/vnd.schemaregistry.v1+json" \
  //  --data '{"compatibility": "BACKWARD"}' \
  //  http://localhost:8081/config/Kafka-value
  //  {"compatibility":"BACKWARD"}
  payload = Source.fromURL(getClass.getResource("/compatibilityBACKWARD.json")).mkString
  result = put(payload,"http://localhost:8081/config/Kafka-value")
  println("Update compatibility requirements under the subject \"Kafka-value\"")
  println("EXPECTING {\"compatibility\":\"BACKWARD\"}")
  println(s"GOT ${result}\r\n")


  //  # Deletes all schema versions registered under the subject "Kafka-value"
  //  $ curl -X DELETE http://localhost:8081/subjects/Kafka-value
  //    [3]
  result = delete("http://localhost:8081/subjects/Kafka-value")
  println("Deletes all schema versions registered under the subject \"Kafka-value\"")
  println("EXPECTING [3]")
  println(s"GOT ${result}\r\n")

  //  # List all subjects
  //  $ curl -X GET http://localhost:8081/subjects
  //    ["Kafka-key"]
  result = get("http://localhost:8081/subjects")
  println("List all subjects")
  println("EXPECTING [\"Kafka-key\"]")
  println(s"GOT ${result}\r\n")


  private[RegistryApp] def post(data: String, url:String)(implicit contentType:ContentType): String = {
    sendData(data, url, HttpMethods.POST, contentType)
  }

  private[RegistryApp] def put(data: String, url:String)(implicit contentType:ContentType): String = {
    sendData(data, url, HttpMethods.PUT, contentType)
  }

  private[RegistryApp] def sendData(data: String, url:String, method:HttpMethod, contentType:ContentType): String = {
    val responseFuture: Future[HttpResponse] =
      Http(system).singleRequest(
        HttpRequest(
          method,
          url,
          entity = HttpEntity(contentType, data.getBytes())
        )
      )
    val html = Await.result(responseFuture.flatMap(x => Unmarshal(x.entity).to[String]), 5 seconds)
    html
  }

  private[RegistryApp] def get(url:String)(implicit contentType:ContentType): String = {
    noBodiedRequest(url, HttpMethods.GET, contentType)
  }

  private[RegistryApp] def delete(url:String)(implicit contentType:ContentType): String = {
    noBodiedRequest(url, HttpMethods.DELETE, contentType)
  }

  private[RegistryApp] def noBodiedRequest(url:String,method:HttpMethod, contentType:ContentType): String = {
    val responseFuture: Future[HttpResponse] = Http(system).singleRequest(HttpRequest(method,url))
    val html = Await.result(responseFuture.flatMap(x => Unmarshal(x.entity).to[String]), 5 seconds)
    html
  }
}

 

 

And this is the output, which I hope is pretty self explanatory now that we have spent some time with the previous explanations/tests. You can read more about the Kafka Schema Registry REST API here : https://docs.confluent.io/current/schema-registry/docs/api.html

 

Register a new version of a schema under the subject “Kafka-key”
EXPECTING {“id”:1}
GOT {“id”:1}

 

Register a new version of a schema under the subject “Kafka-value”
EXPECTING {“id”:1}
GOT {“id”:1}

 

List all subjects
EXPECTING [“Kafka-value”,”Kafka-key”]
GOT [“Kafka-value”,”Kafka-key”]

 

Fetch a schema by globally unique id 1
EXPECTING {“schema”:”\”string\””}
GOT {“schema”:”\”string\””}

 

List all schema versions registered under the subject “Kafka-value”
EXPECTING [1]
GOT [1]

 

Fetch version 1 of the schema registered under subject “Kafka-value”
EXPECTING {“subject”:”Kafka-value”,”version”:1,”id”:1,”schema”:”\”string\””}
GOT {“subject”:”Kafka-value”,”version”:1,”id”:1,”schema”:”\”string\””}

 

Deletes version 1 of the schema registered under subject “Kafka-value”
EXPECTING 1
GOT 1

 

Register the same schema under the subject “Kafka-value”
EXPECTING {“id”:1}
GOT {“id”:1}

 

Deletes the most recently registered schema under subject “Kafka-value”
EXPECTING 2
GOT 2

 

Register the same schema under the subject “Kafka-value”
EXPECTING {“id”:1}
GOT {“id”:1}

 

Fetch the schema again by globally unique id 1
EXPECTING {“schema”:”\”string\””}
GOT {“schema”:”\”string\””}

 

Check whether a schema has been registered under subject “Kafka-key”
EXPECTING {“subject”:”Kafka-key”,”version”:1,”id”:1,”schema”:”\”string\””}
GOT {“subject”:”Kafka-key”,”version”:1,”id”:1,”schema”:”\”string\””}

 

Test compatibility of a schema with the latest schema under subject “Kafka-value”
EXPECTING {“is_compatible”:true}
GOT {“is_compatible”:true}

 

Get top level config
EXPECTING {“compatibilityLevel”:”BACKWARD”}
GOT {“compatibilityLevel”:”BACKWARD”}

 

Update compatibility requirements globally
EXPECTING {“compatibility”:”NONE”}
GOT {“compatibility”:”NONE”}

 

Update compatibility requirements under the subject “Kafka-value”
EXPECTING {“compatibility”:”BACKWARD”}
GOT {“compatibility”:”BACKWARD”}

 

Deletes all schema versions registered under the subject “Kafka-value”
EXPECTING [3]
GOT [3]

 

List all subjects
EXPECTING [“Kafka-key”]
GOT [“Kafka-key”]

 

 

 

 

Conclusion

As with most things in the Confluent platform the Schema Registry is a great bit of kit and easy to use. I urge you all to give it a spin

Leave a comment