title: how to send avro schema ONLY once in kafka
body: <p>I'm using the following code (not really, but let's assume it) to create a schema and send it to kafka by a producer.</p>
  
  <pre><code>public static final String USER_SCHEMA = "{"
          + "\"type\":\"record\","
          + "\"name\":\"myrecord\","
          + "\"fields\":["
          + "  { \"name\":\"str1\", \"type\":\"string\" },"
          + "  { \"name\":\"str2\", \"type\":\"string\" },"
          + "  { \"name\":\"int1\", \"type\":\"int\" }"
          + "]}";
  
  public static void main(String[] args) throws InterruptedException {
      Properties props = new Properties();
      props.put("bootstrap.servers", "localhost:9092");
      props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
      props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
  
      Schema.Parser parser = new Schema.Parser();
      Schema schema = parser.parse(USER_SCHEMA);
      Injection&lt;GenericRecord, byte[]&gt; recordInjection = GenericAvroCodecs.toBinary(schema);
  
      KafkaProducer&lt;String, byte[]&gt; producer = new KafkaProducer&lt;&gt;(props);
  
      for (int i = 0; i &lt; 1000; i++) {
          GenericData.Record avroRecord = new GenericData.Record(schema);
          avroRecord.put("str1", "Str 1-" + i);
          avroRecord.put("str2", "Str 2-" + i);
          avroRecord.put("int1", i);
  
          byte[] bytes = recordInjection.apply(avroRecord);
  
          ProducerRecord&lt;String, byte[]&gt; record = new ProducerRecord&lt;&gt;("mytopic", bytes);
          producer.send(record);
  
          Thread.sleep(250);
  
      }
  
      producer.close();
  }
  </code></pre>
  
  <p>The thing is the code allows me to send only 1 message with this schema. Then I need to change the schema name in order to send the next message... so the name string is a randomly generated one right now so I can send more message. This is a hack so I'd like to know the proper way to do this.</p>
  
  <p>I've also looked at how to send messages without a schema (ie already sent 1 message with schema to kafka now all other messages don't need schema anymore) - but <code>new GenericData.Record(..)</code> expects a schema parameter. If it's null it will throw an error.</p>
  
  <p>So what's the correct way to send avro schema messages to kafka?</p>
  
  <p>Here is another code sample - pretty identical to mine:<br>
  <a href="https://github.com/confluentinc/examples/blob/kafka-0.10.0.1-cp-3.0.1/kafka-clients/producer/src/main/java/io/confluent/examples/producer/ProducerExample.java" rel="nofollow">https://github.com/confluentinc/examples/blob/kafka-0.10.0.1-cp-3.0.1/kafka-clients/producer/src/main/java/io/confluent/examples/producer/ProducerExample.java</a>  </p>
  
  <p>It also doesn't show how to send without setting a schema.</p>