<?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[Stories by Wiraizkandar on Medium]]></title>
        <description><![CDATA[Stories by Wiraizkandar on Medium]]></description>
        <link>https://medium.com/@wiraizkandar?source=rss-3885f7cb6c91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fBIYyqz_deCH074Hqt-Dgg.jpeg</url>
            <title>Stories by Wiraizkandar on Medium</title>
            <link>https://medium.com/@wiraizkandar?source=rss-3885f7cb6c91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:39:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wiraizkandar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Cheap Solutions are Sometime Just Good Enough]]></title>
            <link>https://medium.com/@wiraizkandar/cheap-solutions-are-sometime-just-good-enough-511807eb5be0?source=rss-3885f7cb6c91------2</link>
            <guid isPermaLink="false">https://medium.com/p/511807eb5be0</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Wiraizkandar]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 13:32:14 GMT</pubDate>
            <atom:updated>2026-04-28T13:32:14.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*4F7nED1GK2HoVnFE9hAb9g.png" /></figure><p>When I joined a newly launched API product recently, the business model was straightforward: every successful API response was a charged transaction. In this world, speed and reliability aren’t just “nice to have” — they are the revenue engine.</p><p>At the start, everything was smooth. But as the platform gained traction, the “honeymoon phase” ended. We started feeling the pain of pulling raw transaction data for daily, monthly, and yearly sales reports. What was once a fast query became a massive bottleneck.</p><p>Soon, the complaints started rolling in from the Ops team and the Product Owner. Every time they tried to access the dashboard, it would time out. No report, just a spinning icon. The technical debt was finally asking to be paid, and it wanted it all at once.</p><h3>The Dilemma: Fancy vs. Functional</h3><p>In a world with an infinite budget, the solution is easy: deploy a high-end OLAP database like <strong>ClickHouse</strong>. I’ve benchmarked it before, and it can turn turtle-speed queries into sonic-speed results instantly.</p><p>But we had a real-world constraint: <strong>BUDGET</strong>.</p><p>My goal was to find a solution that was easy to implement and, more importantly, wouldn’t add extra zeros to our monthly cloud bill. I needed a “cheap” win that was just good enough to get the job done.</p><h3>My Strategy: Pre-Aggregation</h3><p>Instead of forcing the database to crunch millions of raw rows every time someone refreshed their browser, I decided to shift the work. Why calculate the same data over and over?</p><p>I chose <strong>Pre-Aggregation</strong>. By summarizing the data into specific periods (day, month, year) ahead of time, we traded expensive real-time math for a simple, lightning-fast row lookup.</p><p><strong>Here is exactly how we did it:</strong></p><ul><li><strong>The 5-Minute Heartbeat:</strong> We set a scheduler to execute every 5 minutes. This keeps the data “fresh” without slamming the server.</li><li><strong>Targeted Querying:</strong> The job only looks at the last 5 minutes of raw transactions. It groups them by unique identifiers — Date, Month, User, or whatever the report needs.</li><li><strong>The ‘Upsert’ Maneuver:</strong> We used an INSERT ... ON DUPLICATE KEY UPDATE query. This handles everything in one go: if the record exists, we update the totals; if not, we create a new summary row.</li><li><strong>The Switch:</strong> Finally, we pointed the reporting dashboard to the new pre-aggregated table instead of the raw transactions table.</li></ul><h3>The Result: From &gt; 30s to &lt; 200ms</h3><p>The outcome was immediate. Reports that used to time out at 30 seconds now return in under <strong>200ms</strong>.</p><p>The best part?</p><ol><li><strong>Cost:</strong> $0 in additional infrastructure fees.</li><li><strong>Simplicity:</strong> No new complex databases to manage.</li><li><strong>Stability:</strong> The raw tables can keep growing, but our dashboard stays fast because it’s only reading the summaries.</li></ol><h3>Final Thought</h3><p>You don’t always need the latest, fanciest tech stack to solve a performance crisis. Before you reach for a heavy (and expensive) tool, look at your architectural flow. Sometimes, a simple shift in when and how you process data is all you need.</p><p>In engineering, a “cheap” solution isn’t a compromise — if it solves the problem efficiently, it’s just smart business.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=511807eb5be0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sync MySQL Data To ClickHouse Database For Better Aggregation Query Performance]]></title>
            <link>https://medium.com/@wiraizkandar/sync-mysql-data-to-clickhouse-database-for-better-aggregation-query-performance-31c920e48a5c?source=rss-3885f7cb6c91------2</link>
            <guid isPermaLink="false">https://medium.com/p/31c920e48a5c</guid>
            <category><![CDATA[clickhouse]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[aggregation]]></category>
            <dc:creator><![CDATA[Wiraizkandar]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 05:17:38 GMT</pubDate>
            <atom:updated>2024-08-25T05:27:06.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*O2qMsZie0sAABiiJspu6Eg.png" /></figure><p>In today’s data-driven landscape, efficient and reliable data synchronisation is crucial for maintaining data integrity and supporting real-time analytics. <a href="https://clickhouse.com/">ClickHouse</a>, a high-performance columnar database management system, stands out as a powerful solution for handling large-scale data with exceptional speed and scalability.</p><p>In this article we will see how to sync our MySQL data in specific table to ClickHouse via MySQL engine. We also will do performance benchmark comparison between Row Oriented Database(MySQL) Vs Column Oriented Database (ClickHouse) in doing aggregation select statement query.</p><p>First , we install our MySQL and ClickHouse database. For this POC we will using localhost environment for both databases.</p><ol><li>Install MySQL — You may using any medium to install your MySQL . In here you may download you installer from MySql official <a href="https://dev.mysql.com/downloads/installer/">site</a>.</li><li>Install ClickHouse — For this POC we will be using quick installation from ClickHouse<a href="https://clickhouse.com/docs/en/install">’ documentation for Linux/MacOS</a></li></ol><p>Once both our databases service are up and ready to play . We will create a database and one table for our POC. In this article we will create a database name “transaction” and a table name “orders”. In this “orders” will have a data on date of transaction data, user id , amount and other relevant data for our use case.</p><p><strong>MySQL Create Table</strong></p><pre>CREATE TABLE `orders` (<br>  `id` bigint NOT NULL AUTO_INCREMENT,<br>  `user_id` bigint NOT NULL,<br>  `amount` decimal(10,2) NOT NULL,<br>  `transaction_type` enum(&#39;debit&#39;,&#39;credit&#39;) NOT NULL,<br>  `transaction_date` date NOT NULL,<br>  `status` enum(&#39;pending&#39;,&#39;completed&#39;,&#39;failed&#39;) NOT NULL,<br>  PRIMARY KEY (`id`),<br>  KEY `date_idx` (`transaction_date`,`status`)<br>) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*pejHz0-n2nVuiYg4ZpQCtg.png" /><figcaption>MySQL orders table structure</figcaption></figure><p><strong>ClickHouse Create Table</strong></p><p>To create ClickHouse orders table we will using clickhouse local client in terminal by navigate to your downloaded clickhouse server and run “./clickhouse”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*XiXdKmAjiWefArjyKqlYZw.png" /></figure><p>And then we will create orders table with Engine to our MySQL orders table with connection credentials.</p><pre>CREATE TABLE orders ( <br>id UInt64, <br>user_id UInt64, <br>amount Decimal(10, 2), <br>transaction_type Enum8(&#39;debit&#39; = 1, &#39;credit&#39; = 2), <br>transaction_date DateTime, <br>status Enum8(&#39;pending&#39; = 1, &#39;completed&#39; = 2, &#39;failed&#39; = 3) )<br>ENGINE = MySQL(<br>  &#39;127.0.0.1:3306&#39;, // Our Mysql Localhost <br>  &#39;transaction&#39;,  // Database Name<br>  &#39;orders&#39;,  // Table Name<br>  &#39;root&#39;, // Mysql User<br>  &#39;Wira12345Q!!!Zt&#39; // Mysql Password<br>);</pre><p>We can verify our table been created by running statement “show tables”. If your orders table appear in the result then we are good to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*KdxSaS6bPjiwVQqGZTcIQg.png" /></figure><p>Seem both our databases are ready for us. To test we can create 1 first record in our MySQL and we should has the same record in our ClickHouse-orders database.</p><p><strong>From </strong>MySQL<strong>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*pcDAGXfteBV2jyu4wyv-PQ.png" /></figure><p><strong>From </strong>ClickHouse<strong>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*NVoKHD7vT7d29y1RDmrDtQ.png" /></figure><p>Awesome!, both tables are linked. For this POC we will be using MySQL <strong>Store Procedure</strong> to pump random data (Around 5 Million Rows) to our MySQL database. We will create a store procedure name as InsertOrders.</p><pre>DELIMITER $$<br><br>CREATE PROCEDURE InsertOrders()<br>BEGIN<br>    DECLARE i INT DEFAULT 1;<br>    <br>    WHILE i &lt;= 5000000 DO<br>        INSERT INTO orders (user_id, amount, transaction_type, transaction_date, status)<br>        VALUES (<br>   FLOOR(5 + RAND()*(500-10)),  <br>            50 + (RAND() * (200 - 50)),  <br>            IF(RAND() &lt; 0.5, &#39;debit&#39;, &#39;credit&#39;), <br>            DATE_ADD(&#39;2023-01-01&#39;, INTERVAL FLOOR(RAND() * 365) DAY),  <br>            ELT(FLOOR(1 + RAND() * 3), &#39;pending&#39;, &#39;completed&#39;, &#39;failed&#39;)<br>            );<br>        SET i = i + 1;<br>    END WHILE;<br>END $$<br><br>DELIMITER ;</pre><p>And execute the store procedure and let it run for sometime so we will have quite some big number of data for our benchmark.</p><pre>CALL InsertOrders();</pre><p>For this POC we will be using around 5 millions of rows to be test for aggregation select statement. Example of select statement we will using.</p><pre>SELECT <br>    status, COUNT(id) AS TotalOrder, SUM(amount) AS TotalSale<br>FROM<br>    orders<br> WHERE<br>     transaction_date &gt;= &#39;2023-01-04&#39;<br>     AND transaction_date &lt;= &#39;2023-01-31&#39;<br>GROUP BY `status`; </pre><p><strong>First Test : 1 (1 Month Record);</strong></p><p>MySQL : 2.143 secs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*Q0Ybg5wbRVS-cAqHFEJc9A.png" /></figure><p>Clikchouse: 1.824 Secs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*B1VRWwqGx3Dbq70ma69aWQ.png" /></figure><p><strong>2nd Test : (6 Months Record)</strong></p><p>MySQL : 15.101 secs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*X48VBDTr5bGIVsrVkL8Fyg.png" /></figure><p>ClickHouse: 1.774 Secs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*ZM-FGygP1gQkDaPqegDyaA.png" /></figure><p><strong>Final Test : (1 Year Record)</strong></p><p>MySQL : (Exceed 30 Secs)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*bHGE0uiGj5mG5WF1pR1Usw.png" /></figure><p>ClickHouse : 2.885 Secs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*HQZMLlNBSFbx1FXkPbI7LA.png" /></figure><p>From this tests we can see ClickHouse has better performance as Column Oriented database to do aggregation select statement for any our use case which need do aggregation such as real-time analytic dashboard and computation for reporting.</p><p>Thank You ~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31c920e48a5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Process AWS SQS Message With Goroutines]]></title>
            <link>https://medium.com/@wiraizkandar/process-aws-sqs-message-with-goroutines-98ff4799ea69?source=rss-3885f7cb6c91------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ff4799ea69</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[goroutines]]></category>
            <dc:creator><![CDATA[Wiraizkandar]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 14:22:12 GMT</pubDate>
            <atom:updated>2024-02-13T14:22:12.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*MvI0H28rzwu7PAle2Rieng.png" /></figure><p>In this article we will create a simple Go worker to process job from AWS SQS with Goroutines to make our Worker process SQS messages concurrently . Goroutines are a key feature of the Go programming language, designed to make concurrent programming easier and more efficient. Essentially, a goroutine is a lightweight thread of execution that’s managed by the Go runtime. They allow functions or methods to be executed concurrently with other parts of a program.</p><p>We will create a Queue blaster script to register dummy jobs that will be process by our Worker. In this case we will use case a job to send a welcome email to our subscribers.</p><p>Create a Go script to schedule job in our SQS queue.</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;math/rand&quot;<br> &quot;os&quot;<br><br> &quot;github.com/aws/aws-sdk-go-v2/aws&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/config&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/credentials&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/service/sqs&quot;<br> &quot;github.com/joho/godotenv&quot;<br>)<br><br>var dummyEmailAddresses = [5]string{<br> &quot;wiraizkandar@gmail.com&quot;,<br> &quot;werawhayek@gmail.com&quot;,<br> &quot;hishamanakhashim@gmail.com&quot;,<br> &quot;hashimanakjamal@gmail.com&quot;,<br> &quot;jamalanakharam@gmail.com&quot;,<br>}<br><br>// Define the AWS Config and Credentials to use<br><br>type MessageBody struct {<br> ToEmailAddress string<br> Subject        string<br> Content        string<br>}<br><br>type Message struct {<br> MessageID   int         `json:&quot;message_id&quot;`<br> JobType     string      `json:&quot;job_type&quot;`<br> MessageBody MessageBody `json:&quot;message_body&quot;`<br>}<br><br>func main() {<br><br> err := godotenv.Load()<br> if err != nil {<br>  log.Fatal(&quot;Error loading .env file&quot;)<br> }<br><br> <br> cfg, err := config.LoadDefaultConfig(context.TODO(),<br>  config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(os.Getenv(&quot;AWS_SQS_KEY&quot;), os.Getenv(&quot;AWS_SQS_SECRET&quot;), &quot;&quot;)),<br>  config.WithRegion(os.Getenv(&quot;AWS_SQS_REGION&quot;)),<br> )<br><br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> / Using the Config value, create the SQS client<br> sqsClient := sqs.NewFromConfig(cfg)<br><br> // Define the URL of the queue<br> sqsUrl := os.Getenv(&quot;AWS_SQS_URL&quot;)<br><br> messageIdCounter := 1<br><br> // we are going to take random data from the dummy data<br><br> for {<br>  message := Message{<br>   MessageID: messageIdCounter,<br>   JobType:   &quot;SendWelcomeEmailJob&quot;,<br>   MessageBody: MessageBody{<br>    ToEmailAddress: dummyEmailAddresses[rand.Intn(len(dummyEmailAddresses))],<br>    Subject:        &quot;Welcome To My Channel!&quot;,<br>    Content:        &quot;What&#39;s Up!, welcome to my channel!&quot;,<br>   },<br>  }<br><br>  jsonMessage, err := json.Marshal(message)<br><br>  if err != nil {<br>   log.Fatalln(&quot;Failed to marshal message:&quot;, err)<br>  }<br><br>  messagePayload := &amp;sqs.SendMessageInput{<br>   MessageBody: aws.String(string(jsonMessage)),<br>   QueueUrl:    &amp;sqsUrl,<br>  }<br><br>  _, err = sqsClient.SendMessage(context.TODO(), messagePayload)<br><br>  if err != nil {<br>   log.Fatalf(&quot;unable to send message, %v&quot;, err)<br>  }<br><br>  fmt.Println(&quot;Message Queued ID: &quot;, messageIdCounter)<br><br>  messageIdCounter++<br><br> }<br>}</pre><p>Next, create our Worker to process message from SQS. In this code we will using static credential configuration which is we will using .env file variable for our AWS config.</p><pre>func setAWSConfig() {<br> AWS_SQS_KEY = os.Getenv(&quot;AWS_SQS_KEY&quot;)<br> AWS_SQS_SECRET = os.Getenv(&quot;AWS_SQS_SECRET&quot;)<br> AWS_SQS_URL = os.Getenv(&quot;AWS_SQS_URL&quot;)<br> AWS_SQS_REGION = os.Getenv(&quot;AWS_SQS_REGION&quot;)<br>}</pre><pre>// Using the SDK&#39;s default configuration, loading additional config<br> // and credentials values from the environment variables, shared<br> // credentials, and shared configuration files<br> cfg, err := config.LoadDefaultConfig(context.TODO(),<br>  config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(AWS_SQS_KEY, AWS_SQS_SECRET, &quot;&quot;)),<br>  config.WithRegion(AWS_SQS_REGION),<br> )<br><br> if err != nil {<br>  log.Fatal(err)<br> }</pre><p>In this section we will set 10 as our max number of messages for every pulling from SQS</p><pre>results, err := sqsClient.ReceiveMessage(<br>   context.Background(),<br>   &amp;sqs.ReceiveMessageInput{<br>    QueueUrl:            &amp;AWS_SQS_URL,<br>    MaxNumberOfMessages: 10,<br>   },<br>  )</pre><p>In this section we will start process messages we received from SQS and add waitGroup</p><pre>for _, message := range results.Messages {<br><br>   wg.Add(1)<br><br>   go processJob(message, sqsClient)<br><br>   wg.Wait()<br>  }</pre><p>The full script for our sqsworker.go will be look like this:</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;sync&quot;<br><br> &quot;github.com/aws/aws-sdk-go-v2/aws&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/config&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/credentials&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/service/sqs&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/service/sqs/types&quot;<br> &quot;github.com/joho/godotenv&quot;<br>)<br><br>var (<br> AWS_SQS_KEY    string<br> AWS_SQS_SECRET string<br> AWS_SQS_URL    string<br> AWS_SQS_REGION string<br> wg             sync.WaitGroup<br>)<br><br>func main() {<br><br> err := godotenv.Load()<br> if err != nil {<br>  log.Fatal(&quot;Error loading .env file&quot;)<br> }<br><br> // Load AWS Config<br> setAWSConfig()<br><br> // Using the SDK&#39;s default configuration, loading additional config<br> // and credentials values from the environment variables, shared<br> // credentials, and shared configuration files<br> cfg, err := config.LoadDefaultConfig(context.TODO(),<br>  config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(AWS_SQS_KEY, AWS_SQS_SECRET, &quot;&quot;)),<br>  config.WithRegion(AWS_SQS_REGION),<br> )<br><br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> // Using the Config value, create the SQS client<br> sqsClient := sqs.NewFromConfig(cfg)<br><br> // Receive messages from SQS<br> for {<br>  results, err := sqsClient.ReceiveMessage(<br>   context.Background(),<br>   &amp;sqs.ReceiveMessageInput{<br>    QueueUrl:            &amp;AWS_SQS_URL,<br>    MaxNumberOfMessages: 10,<br>   },<br>  )<br><br>  if err != nil {<br>   log.Fatal(err)<br>  }<br><br>  for _, message := range results.Messages {<br><br>   wg.Add(1)<br><br>   go processJob(message, sqsClient)<br><br>   wg.Wait()<br>  }<br> }<br><br>}<br><br>func setAWSConfig() {<br> AWS_SQS_KEY = os.Getenv(&quot;AWS_SQS_KEY&quot;)<br> AWS_SQS_SECRET = os.Getenv(&quot;AWS_SQS_SECRET&quot;)<br> AWS_SQS_URL = os.Getenv(&quot;AWS_SQS_URL&quot;)<br> AWS_SQS_REGION = os.Getenv(&quot;AWS_SQS_REGION&quot;)<br>}<br><br>func processJob(message types.Message, sqsClient *sqs.Client) {<br> defer wg.Done()<br><br> deleteParams := &amp;sqs.DeleteMessageInput{<br>  QueueUrl:      aws.String(AWS_SQS_URL),<br>  ReceiptHandle: message.ReceiptHandle,<br> }<br> // Process message here<br> log.Println(*message.Body)<br><br> _, err := sqsClient.DeleteMessage(context.TODO(), deleteParams)<br><br> if err != nil {<br>  log.Fatal(err)<br> }<br>}</pre><p>Let’s start send message into our SQS queue by execute our sender.go and our job should send in sequence message queue id.</p><pre>go run sender.go</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ZIxQCUDnZIrIXaiF6Pwedg.png" /></figure><p>Next, we will start of Worker by execute</p><pre>go run sqsworker.go</pre><p>We will see our jobs are not process in sequence message queue ID because of our Goroutines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpwZ1uNQ9lFRiqydAaavuA.png" /></figure><p>Nice! Our worker is ready to process message from our SQS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ff4799ea69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka + (Producer & Consumer) In Local Docker with Go]]></title>
            <link>https://medium.com/@wiraizkandar/kafka-producer-consumer-in-local-docker-with-go-02759d20fde6?source=rss-3885f7cb6c91------2</link>
            <guid isPermaLink="false">https://medium.com/p/02759d20fde6</guid>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[gỗ]]></category>
            <dc:creator><![CDATA[Wiraizkandar]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 15:18:53 GMT</pubDate>
            <atom:updated>2024-02-01T15:18:53.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*-Ld15DcghVeH3zOhS6YKFQ.png" /></figure><p>Here we will create Kafka producer and consumer with Kafka docker container.</p><p>In general idea how Kafka works. Producer will send message for a topic to Kafka and Consumer will pull and consume the message from Kafka according which topic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lYkwFOZ7H6lAXdP3JOMbw.png" /></figure><p><strong>Producer</strong> — A Kafka Producer is responsible for sending records (messages) to Kafka topics. It is a client application or system that generates data and publishes it to a Kafka cluster.</p><p><strong>Consumer</strong> — A Kafka Consumer is a client application or system that subscribes to and processes records from Kafka topics. It retrieves data from topics and consumes it for further processing.</p><p>Here we will create simulation for situation a system produce user social media “<strong>like</strong>” a social media post action such as ”love”, “like”, “hate”, “smile”, “cry”</p><p>We are going to create local Kafka environment using docker . You may <a href="https://docs.docker.com/get-docker/">install Docker and Docker compose</a> before create Docker container.</p><p>Create docker-compose.yml file to configure our Kafka container.</p><pre># docker-compose.yml<br>version: &quot;3.7&quot;<br>services:<br>  zookeeper:<br>    restart: always<br>    container_name: kafka-like-zookeeper<br>    image: docker.io/bitnami/zookeeper:3.8<br>    ports:<br>      - &quot;2181:2181&quot;<br>    volumes:<br>      - &quot;zookeeper-volume:/bitnami&quot;<br>    environment:<br>      - ALLOW_ANONYMOUS_LOGIN=yes<br>  kafka:<br>    restart: always<br>    container_name: kafka-like<br>    image: docker.io/bitnami/kafka:3.3<br>    ports:<br>      - &quot;9093:9093&quot;<br>    volumes:<br>      - &quot;kafka-volume:/bitnami&quot;<br>    environment:<br>      - KAFKA_BROKER_ID=1<br>      - KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper:2181<br>      - ALLOW_PLAINTEXT_LISTENER=yes<br>      - KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CLIENT:PLAINTEXT,EXTERNAL:PLAINTEXT<br>      - KAFKA_CFG_LISTENERS=CLIENT://:9092,EXTERNAL://:9093<br>      - KAFKA_CFG_ADVERTISED_LISTENERS=CLIENT://kafka:9092,EXTERNAL://localhost:9093<br>      - KAFKA_CFG_INTER_BROKER_LISTENER_NAME=CLIENT<br>    depends_on:<br>      - zookeeper<br>volumes:<br>  kafka-volume:<br>  zookeeper-volume:</pre><p>From our docker-compose.yml, we will using zookeeper to manage kafka broker and we will use port 9093 for our Kafka container. For Kafka container configuration can refer to <a href="https://hub.docker.com/r/bitnami/kafka">Docker Hub</a></p><p>Once our docker-compose.yml ready run “docker compose up -d” and “docker ps”</p><pre>docker compose up -d</pre><p>You should be able to see your docker containers are ready to be use</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uroyhOdUc9CrYoLlrW1-Gg.png" /></figure><p>Once our Kafka container is ready , we will need to create topic to our Kafka. Go into your Kafka container in your terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*2mV-SfHF3tFR7chfcPpZ-g.png" /></figure><pre>docker exec -it kafka-like /bin/bash</pre><p>Create Topic</p><pre>kafka-topics.sh --create --topic post-likes --bootstrap-server localhost:9092 --partitions 1 --replication-factor 1</pre><p>Show Topics</p><pre>kafka-topics.sh --list --bootstrap-server localhost:9092</pre><p>You should be able to see your topic “post-likes” already created then we are ready to push message to “post-likes” topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*7G_BaqzLBdOVB84Qd7P0zQ.png" /></figure><p>For this simulation we will use Go as our application programming language. We will create a producer.go as our “<strong>Producer</strong>” and consumer.go as our “<strong>Consumer</strong>”</p><p>In this program we will use <a href="https://github.com/IBM/sarama">sarama</a> package . Install sarama in our Go application</p><pre>go get github.com/IBM/sarama</pre><p>In this example we will use</p><pre>Topic : post-likes<br>Consumer Group ID : consumer-group</pre><p>Create file producer.go for dummy Producer. In this producer, we will send a JSON message with random action and user id to our Kafka.</p><pre>package main<br><br>import (<br> &quot;encoding/json&quot;<br> &quot;log&quot;<br> &quot;math/rand&quot;<br> &quot;os&quot;<br><br> &quot;github.com/IBM/sarama&quot;<br>)<br><br>type Message struct {<br> UserId     int    `json:&quot;user_id&quot;`<br> PostId     string `json:&quot;post_id&quot;`<br> UserAction string `json:&quot;user_action&quot;`<br>}<br><br>func main() {<br> brokers := []string{&quot;localhost:9093&quot;}<br> producer, err := sarama.NewSyncProducer(brokers, nil)<br> if err != nil {<br>  log.Fatalln(&quot;Failed to start Sarama producer:&quot;, err)<br>  os.Exit(1)<br> }<br><br> // Dummy Data<br> userId := [5]int{100001, 100002, 100003, 100004, 100005}<br> postId := [5]string{&quot;POST00001&quot;, &quot;POST00002&quot;, &quot;POST00003&quot;, &quot;POST00004&quot;, &quot;POST00005&quot;}<br> userAction := [5]string{&quot;love&quot;, &quot;like&quot;, &quot;hate&quot;, &quot;smile&quot;, &quot;cry&quot;}<br><br> for {<br>  // we are going to take random data from the dummy data<br>  message := Message{<br>   UserId:     userId[rand.Intn(len(userId))],<br>   PostId:     postId[rand.Intn(len(postId))],<br>   UserAction: userAction[rand.Intn(len(userAction))],<br>  }<br><br>  jsonMessage, err := json.Marshal(message)<br><br>  if err != nil {<br>   log.Fatalln(&quot;Failed to marshal message:&quot;, err)<br>   os.Exit(1)<br>  }<br><br>  msg := &amp;sarama.ProducerMessage{<br>   Topic: &quot;post-likes&quot;,<br>   Value: sarama.StringEncoder(jsonMessage),<br>  }<br><br>  _, _, err = producer.SendMessage(msg)<br>  if err != nil {<br>   log.Fatalln(&quot;Failed to send message:&quot;, err)<br>   os.Exit(1)<br>  }<br>  log.Println(&quot;Message sent!&quot;)<br> }<br>}</pre><p>Create consumer.go as our Consumer. In this consumer we will set auto commit as true. This is important to let our consumer will not consume the same message more than one.</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;log&quot;<br> &quot;time&quot;<br><br> &quot;github.com/IBM/sarama&quot;<br>)<br><br>type exampleConsumerGroupHandler struct{}<br><br>func (exampleConsumerGroupHandler) Setup(_ sarama.ConsumerGroupSession) error   { return nil }<br>func (exampleConsumerGroupHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil }<br>func (h exampleConsumerGroupHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {<br> for msg := range claim.Messages() {<br>  log.Printf(&quot;Received message: %s\n&quot;, string(msg.Value))<br>  // Process the message as per your requirement here<br>  sess.MarkMessage(msg, &quot;&quot;)<br> }<br> return nil<br>}<br><br>func main() {<br> brokers := []string{&quot;localhost:9093&quot;}<br> groupID := &quot;consumer-group&quot;<br><br> config := sarama.NewConfig()<br> config.Version = sarama.V2_0_0_0 // specify appropriate Kafka version<br> config.Consumer.Offsets.AutoCommit.Enable = true<br> config.Consumer.Offsets.AutoCommit.Interval = 1 * time.Second<br><br> consumerGroup, err := sarama.NewConsumerGroup(brokers, groupID, config)<br> if err != nil {<br>  log.Panicf(&quot;Error creating consumer group client: %v&quot;, err)<br> }<br><br> ctx := context.Background()<br><br> for {<br>  err := consumerGroup.Consume(ctx, []string{&quot;post-likes&quot;}, exampleConsumerGroupHandler{})<br>  if err != nil {<br>   log.Panicf(&quot;Error from consumer: %v&quot;, err)<br>  }<br> }<br>}</pre><p>Once you both producer.go and consumer.go is ready, run our producer to start produce message to Kafka.</p><pre>go run producer.go</pre><p>You should start see our producer start blast dummy message to our Kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*c_PO_QhF8m3lmxcQIIfNdw.png" /></figure><p>The next step is run our consumer.go to start consume message from Kafka.</p><pre>go run consumer.go</pre><p>You should see our consumer start consume message from Kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*5D-7Z12ADy3CfuMXGOpE6g.png" /></figure><p>That’s all!. Your are ready to build your own Producer and Consumer for your own use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02759d20fde6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Docker Container For Cassandra Database]]></title>
            <link>https://medium.com/@wiraizkandar/create-docker-container-for-cassandra-database-ec9ea426a018?source=rss-3885f7cb6c91------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec9ea426a018</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cassandra]]></category>
            <dc:creator><![CDATA[Wiraizkandar]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 16:02:08 GMT</pubDate>
            <atom:updated>2024-01-18T16:39:04.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHlwt2II3nI4TE_bl32tsA.jpeg" /></figure><p>We will create a Cassandra docker container for our access token table. Cassandra has high scalability which is suitable for our use case to has high traffic for access token validation.</p><p>We are going to create Cassandra database with credential</p><ul><li>User = root</li><li>Password = password</li></ul><ol><li><strong>Create docker-compose yml file</strong></li></ol><pre>version: &#39;3&#39;<br>services:<br>  cassandra:<br>    image: cassandra:latest<br>    environment:<br>      - CASSANDRA_USER=root<br>      - CASSANDRA_PASSWORD=password<br>    ports:<br>      - &quot;9042:9042&quot;<br>    volumes:<br>      - cassandra_data:/var/lib/cassandra<br><br>volumes:<br>  cassandra_data:</pre><p><strong>2. Run docker compose</strong></p><pre>docker-compose up -d</pre><p>to check is your container has been created you may run</p><pre>docker ps</pre><p>You should be able to see a container with cassandra:latest image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*_F3yGLAo3Kz-l8nzv6VUBQ.png" /></figure><p><strong>3. Connect your DB client with Cassandra database and create keyspace and table for our access tokens table.</strong></p><p>In here, i’m using <a href="https://www.jetbrains.com/datagrip/">DataGrip</a> application from Jetbrain as my Cassandra client . You may connect to your Cassandra database by using host “<strong>127.0.0.1”</strong> at port “<strong>9042”</strong> same as in our yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xssZ8_4omhiwN1PXQdG_nw.png" /></figure><p>We will create keyspace “oauth” (as in mysql it similar to database name)</p><pre>CREATE KEYSPACE oauth <br>WITH REPLICATION = { &#39;class&#39; : &#39;SimpleStrategy&#39;, &#39;replication_factor&#39; : 1 };</pre><p>- `<strong>SimpleStrategy</strong>` is a replication strategy that is suitable for a single-datacenter deployment. It places the first replica on a node determined by the partitioner, and additional replicas on the next nodes clockwise in the ring.</p><p>- `<strong>replication_factor</strong>` is an option that specifies the number of replicas of data on multiple nodes. A `replication_factor` of 1 means that there is only one copy of each row on one node.</p><p>Create access_tokens table</p><pre>CREATE TABLE oauth.access_tokens (<br>    user_id varchar,<br>    access_token text,<br>    expiry timestamp,<br>    is_revoke boolean,<br>    PRIMARY KEY (user_id, access_token)<br>);</pre><p>Try insert data</p><pre>INSERT INTO oauth.access_tokens (user_id, access_token, expiry, is_revoke)<br>VALUES (&#39;100001&#39;, &#39;123456&#39;, &#39;2024-01-19T12:00:00Z&#39;, false);</pre><pre>select * from oauth.access_tokens;</pre><p>You should able to see the inserted record</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*6FEhIP2nocxmEeXCKRqeYA.png" /></figure><p>You are good to go! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec9ea426a018" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Use Docker In Laravel For Local Development]]></title>
            <link>https://medium.com/@wiraizkandar/how-to-use-docker-in-laravel-for-local-development-e684b67ff41b?source=rss-3885f7cb6c91------2</link>
            <guid isPermaLink="false">https://medium.com/p/e684b67ff41b</guid>
            <dc:creator><![CDATA[Wiraizkandar]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 11:52:21 GMT</pubDate>
            <atom:updated>2023-12-20T12:04:47.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfPd1xkP9pbzo84ZXz5EYg.jpeg" /></figure><p>Docker has become an invaluable tool for developers looking to streamline their local development environments, and when combined with Laravel, a popular PHP framework, it can significantly enhance the ease and consistency of development workflows. Docker allows you to create isolated containers that encapsulate your application’s dependencies and environment, making it easier to set up, share, and replicate development environments across different machines. In this guide, we will walk you through the essential steps to use Docker in Laravel for local development.</p><p>In this steps we will be using :</p><ul><li>MySQL</li><li>Nginx</li><li>NPM</li><li>Composer</li></ul><h4>Step 1 : Create ‘src’ Folder Structure</h4><pre>&lt; YourAppFolder &gt;<br>  &lt; src &gt;</pre><p>In this src folder your Laravel project will stored.</p><h4>Step 2 : Create docker-compose.yaml file.</h4><pre>&lt; YourAppFolder &gt;<br>  &lt; src &gt;<br>  docker-compose.yaml</pre><h4><strong>Step 3 : Configure NGINX image in docker-compose.yaml</strong></h4><pre>version: &#39;3.8&#39;<br><br>networks:<br>  laravel:<br>    name: laravel<br><br>services:<br>  nginx:<br>    build:<br>      context: .<br>      dockerfile: nginx.dockerfile<br>    container_name: nginx<br>    depends_on:<br>      - mysql<br>      - php<br>    ports:<br>      - &quot;3000:80&quot;<br>      - &quot;8443:443&quot;<br>    volumes:<br>      - ./src:/var/www/html<br>    networks:<br>      - laravel</pre><p>In this section we will set</p><ol><li>Network name as “laravel”</li><li>NGINX container as “nginx”</li><li>Expose port 3000 and 8443</li></ol><p>We set our docker network as “Laravel” and we set depends_on for <strong>mysql</strong> and <strong>php</strong> which is will we set in the next step. The reason we set this depends_on mysql and php . we want our nginx compose after mysql and php container.</p><p>Create our NGINX dockerfile</p><pre>Create docker file for nginx<br>FROM nginx:stable-alpine<br><br>ADD ./nginx/default.conf /etc/nginx/conf.d/default.conf<br><br>RUN mkdir -p /var/www/html<br><br>RUN mkdir -p /etc/nginx/certs/mkcert<br><br>ADD ./nginx/certs/ /etc/nginx/certs/mkcert</pre><p><strong>Step 4 : Configure your MySQL container</strong></p><pre>mysql:<br>    image: mysql:8.1.0<br>    container_name: mysql<br>    ports:<br>      - &quot;4306:3306&quot;<br>    volumes:<br>      - ./mysql:/var/lib/mysql<br>    environment:<br>      MYSQL_DATABASE : laraveldb<br>      MYSQL_USER : laravel<br>      MYSQL_PASSWORD : password<br>      MYSQL_ROOT_PASSWORD: password<br>    networks:<br>      - laravel</pre><p>in this section will be using port 4306 for your mysql client connection</p><p><strong>Step 5: Configure composer container</strong></p><pre>composer:<br>    image: composer:latest<br>    container_name: composer<br>    volumes:<br>      - ./src:/var/www/html<br>    working_dir: /var/www/html<br>    networks:<br>      - laravel</pre><p>in this section will configure composer image which is will much easier for us to use composer for our <strong>Laravel</strong> application.</p><p><strong>Step 6: Configure artisan image</strong></p><pre>artisan:<br>    build:<br>      context: .<br>      dockerfile: php.dockerfile<br>    container_name: artisan<br>    volumes:<br>      - ./src:/var/www/html<br>    working_dir: /var/www/html<br>    entrypoint:<br>      - php<br>      - artisan<br>    networks:<br>      - laravel</pre><p>in this section we will set image for our artisan container</p><p><strong>Step 7: Configure our NPM container</strong></p><pre>  npm:<br>    image: node:latest<br>    container_name: npm<br>    volumes:<br>      - ./src:/var/www/html<br>      - ./nginx/certs:/etc/vite/certs<br>    working_dir: /var/www/html<br>    ports:<br>      - &quot;5173:5173&quot;<br>      - &quot;3001:3001&quot;<br>    entrypoint:<br>      - npm<br>    networks:<br>      - laravel</pre><p>in this section we will set image for our NPM container will be use for our npm command and expose port for 5173 for our <a href="https://vitejs.dev/">Vite</a>.</p><p><strong>Step 8 : Configure our PHP container</strong></p><pre>  php:<br>    build:<br>      context: .<br>      dockerfile: php.dockerfile<br>    container_name: php<br>    volumes:<br>      - ./src:/var/www/html<br>    networks:<br>      - laravel</pre><p>Create our PHP dockerfile</p><pre>FROM php:8.1-fpm-alpine<br><br>RUN mkdir -p /var/www/html<br><br>RUN apk --no-cache add shadow &amp;&amp; usermod -u 1000 www-data<br><br>RUN docker-php-ext-install pdo pdo_mysql</pre><p><strong>Step 8 : Set </strong>NGINX<strong> conf file</strong></p><p>Create a folder name NGINX at your root document as sub folder certs to easy manage your SSL certs.</p><pre>&lt; YourAppFolder &gt;<br>  &lt; src &gt;<br>  &lt; nginx &gt;<br>    &lt; certs &gt;</pre><p>Create a default.conf file in the nginx folder</p><pre>server {<br>    listen 80 default_server;<br><br>    server_name _;<br><br>    return 301 https://$host$request_uri;<br>}<br><br>server {<br>    listen 443 ssl;<br>    index index.php index.html;<br>    server_name localhost;<br>    root /var/www/html/public;<br><br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br><br>    location ~ \.php$ {<br>        try_files $uri =404;<br>        fastcgi_split_path_info ^(.+\.php)(/.+)$;<br>        fastcgi_pass php:9000;<br>        fastcgi_index index.php;<br>        include fastcgi_params;<br>        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;<br>        fastcgi_param PATH_INFO $fastcgi_path_info;<br>    }<br><br>    ssl_certificate /etc/nginx/certs/mkcert/laraveldocker.test.pem;<br>    ssl_certificate_key /etc/nginx/certs/mkcert/laraveldocker.test-key.pem;<br>}<br><br>server {<br>    listen 80;<br>    index index.php index.html;<br>    server_name _;<br>    root /var/www/html/public;<br><br>    location / {<br>        try_files $uri $uri/ /index.php?$query_string;<br>    }<br><br>    location ~ \.php$ {<br>        try_files $uri =404;<br>        fastcgi_split_path_info ^(.+\.php)(/.+)$;<br>        fastcgi_pass php:9000;<br>        fastcgi_index index.php;<br>        include fastcgi_params;<br>        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;<br>        fastcgi_param PATH_INFO $fastcgi_path_info;<br>    }<br>}</pre><p><strong>Step 9 : Set MySQL data folder</strong></p><p>Create a folder name mysql to hold all your database data.</p><pre>&lt; YourAppFolder &gt;<br>  &lt; src &gt;<br>  &lt; nginx &gt;<br>    &lt; certs &gt;<br>  &lt; mysql &gt;</pre><p><strong>Step 10 : Run your docker environment</strong></p><pre>docker compose up -d</pre><p>Thank you!~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e684b67ff41b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>