<?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 Vishal Jain on Medium]]></title>
        <description><![CDATA[Stories by Vishal Jain on Medium]]></description>
        <link>https://medium.com/@vishalj64?source=rss-24887eee8868------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*36zLmptm7h9HR2Wuzu0nZw.jpeg</url>
            <title>Stories by Vishal Jain on Medium</title>
            <link>https://medium.com/@vishalj64?source=rss-24887eee8868------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:59:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vishalj64/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[Efficiently Filling Arrays and Slices in Go: A Performance Guide]]></title>
            <link>https://towardsdev.com/efficiently-filling-arrays-and-slices-in-go-a-performance-guide-b43432dbd430?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/b43432dbd430</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[go-programming]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 11:06:24 GMT</pubDate>
            <atom:updated>2025-02-17T16:31:38.922Z</atom:updated>
            <content:encoded><![CDATA[<p>When working on a Go project, you might need to fill a slice or array with a repeating pattern. Recently, I explored different approaches to achieve this efficiently and discovered a powerful way to boost performance. In this article, I’ll walk through various techniques to fill a slice in Go, highlight their performance differences, and explain why one method stands out as significantly faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*LCabmJSwOs3zqlLI24r1rA.png" /></figure><h3>Why Slice Filling Matters</h3><p>For my toy project, I needed to fill a background buffer with a specific RGB color pattern. Optimizing this operation significantly improved my achievable frame rate. The insights I gained could be useful for anyone working with large datasets, graphics programming, or high-performance applications.</p><p>All tests were performed on a buffer of 73,437 bytes, allocated as:</p><pre>var bigSlice = make([]byte, 73437)</pre><p>Let’s compare three common ways to fill this slice.</p><h4>Index-based Loop</h4><p>The simplest way is to iterate through each index and set the value.</p><pre>func FillSliceIndex(slice []byte, value byte) {<br>    for j := 0; j &lt; len(slice); j++ {<br>        slice[j] = value<br>    }<br>}<br><br>func Benchmark_FillsliceIndex(b *testing.B) {<br>    slice := make([]byte, 73437)<br>    for i := 0; i &lt; b.N; i++ {<br>        FillSliceIndex(slice, 65)<br>    }<br>}</pre><p><strong>Benchmark Results:</strong></p><pre>| Name                        | Executions | Time/Op      | Bytes/Op | Allocs/Op   |<br>| --------------------------- | ---------- | ------------ | -------- | ----------- |<br>| Benchmark_FillsliceIndex-4  | 24,945     | 45,540 ns/op | 0 B/op   | 0 allocs/op |</pre><h4>Range-based Loop</h4><p>Using a <strong><em>range</em></strong> loop provides a slight performance improvement:</p><pre>func FillSliceRange(slice []byte, value byte) {<br>    for j := range slice {<br>        slice[j] = value<br>    }<br>}<br><br>func Benchmark_FillsliceRange(b *testing.B) {<br>    slice := make([]byte, 73437)<br>    for i := 0; i &lt; b.N; i++ {<br>        FillSliceRange(slice, 66)<br>    }<br>}</pre><p><strong>Benchmark Results:</strong></p><pre>| Name                        | Executions | Time/Op      | Bytes/Op | Allocs/Op   |<br>| --------------------------- | ---------- | ------------ | -------- | ----------- |<br>| Benchmark_FillsliceRange-4  | 35,086     | 34,316 ns/op | 0 B/op   | 0 allocs/op |</pre><h4>The Copy Trick (Efficient Method)</h4><p>The most efficient approach leverages Go’s built-in <strong><em>copy</em></strong> function to fill the slice incrementally:</p><pre>func FillSliceCopyTrick(slice []byte, value byte) {<br>    slice[0] = value<br>    for j := 1; j &lt; len(slice); j *= 2 {<br>        copy(slice[j:], slice[:j])<br>    }<br>}<br><br>func Benchmark_FillsliceCopyTrick(b *testing.B) {<br>    slice := make([]byte, 73437)<br>    for i := 0; i &lt; b.N; i++ {<br>        FillSliceCopyTrick(slice, 67)<br>    }<br>}</pre><p><strong>Benchmark Results:</strong></p><pre>| Name                            | Executions | Time/Op     | Bytes/Op | Allocs/Op   |<br>| ------------------------------- | ---------- | ----------- | -------- | ----------- |<br>| Benchmark_FillsliceCopyTrick-4  | 749,976    | 1,579 ns/op | 0 B/op   | 0 allocs/op |</pre><h4>Filling with a Multi-Element Pattern</h4><p>If you need to fill the slice with a repeating multi-byte pattern, you can adapt the copy trick easily:</p><pre>func FillSlicePatternCopyTrick(slice []byte, pattern []byte) {<br>    copy(slice, pattern)<br>    for j := len(pattern); j &lt; len(slice); j *= 2 {<br>        copy(slice[j:], slice[:j])<br>    }<br>}<br><br>func Benchmark_FillslicePatternCopyTrick(b *testing.B) {<br>    slice := make([]byte, 73437)<br>    pattern := []byte{0xde, 0xad, 0xbe, 0xef}<br>    for i := 0; i &lt; b.N; i++ {<br>        FillSlicePatternCopyTrick(slice, pattern)<br>    }<br>}</pre><p><strong>Benchmark Results:</strong></p><pre>| Name                                   | Executions | Time/Op     | Bytes/Op | Allocs/Op   |<br>| -------------------------------------- | ---------- | ----------- | -------- | ----------- |<br>| Benchmark_FillslicePatternCopyTrick-4  | 798,944    | 1,563 ns/op | 0 B/op   | 0 allocs/op |</pre><h4>Summary of Benchmark Results</h4><pre>| Name                                   | Executions | Time/Op      | Bytes/Op | Allocs/Op   |<br>| -------------------------------------- | ---------- | ------------ | -------- | ----------- |<br>| Benchmark_FillsliceIndex-4             | 24,945     | 45,540 ns/op | 0 B/op   | 0 allocs/op |<br>| Benchmark_FillsliceRange-4             | 35,086     | 34,316 ns/op | 0 B/op   | 0 allocs/op |<br>| Benchmark_FillsliceCopyTrick-4         | 749,976    | 1,579 ns/op  | 0 B/op   | 0 allocs/op |<br>| Benchmark\_FillslicePatternCopyTrick-4 | 798,944    | 1,563 ns/op  | 0 B/op   | 0 allocs/op |</pre><h4>How and Why the Copy Trick Works</h4><p>The <strong><em>copy</em></strong> function avoids the overhead of indexing and bounds checking each element. Here’s how it works:</p><ul><li>The first value (or pattern) is loaded into the slice.</li><li>Each call to `copy` duplicates twice the amount of data as the previous iteration.</li><li>This exponential growth reduces the number of copy operations required, amortizing the cost.</li><li>The final copy naturally stops when the slice is filled — no bounds checks are needed.</li></ul><h4>Final Thoughts</h4><p>If you ever need to efficiently fill a slice or array in Go, especially for large datasets, the copy trick is a powerful and elegant solution. It’s faster, avoids unnecessary allocations, and leverages built-in optimizations for block memory operations.</p><p>I hope this guide helps you optimize your Go code and improve your application’s performance. Let me know if you discover any other cool slice-filling techniques!</p><p>Happy coding! 🚀</p><h4>Reference</h4><p>For the complete source code and more details, check out the <a href="https://github.com/Vishalj32/sliceFillExample.git">GitHub</a> repository</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b43432dbd430" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/efficiently-filling-arrays-and-slices-in-go-a-performance-guide-b43432dbd430">Efficiently Filling Arrays and Slices in Go: A Performance Guide</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLD System Design Series: Snake And Ladders in Go]]></title>
            <link>https://towardsdev.com/lld-system-design-series-snake-and-ladders-in-go-a5f34887a14b?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5f34887a14b</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 16:40:36 GMT</pubDate>
            <atom:updated>2024-10-07T18:01:09.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*UZyQbXip7DXSzuIwlUO_lA.jpeg" /><figcaption>Snakes and Ladders Board Game</figcaption></figure><p>Snake and Ladder is a classic board game that’s been a favorite among families and friends for generations. It’s simple yet incredibly fun, with snakes sending you backward and ladders helping you climb up. But what if we could automate the gameplay?</p><p>In this article, I’ll walk you through approach machine coding for <strong>Snakes and Ladders</strong> using <strong>Go</strong>. We’ll dive into how to handle the board setup, player movements, and win conditions, and in the end, you’ll have a functional game that can be customized for multiple players.</p><h3>Problem Statement</h3><p>The goal of the game is simple: Players roll a dice and move forward on a 100-cell board. The challenge lies in navigating the snakes and ladders. If a player lands on a snake’s head, they slide down to its tail. If they land at the base of a ladder, they climb to the top. The first player to land exactly on the 100th cell wins.</p><h3>Inputs</h3><p>The game accepts input in the following format:</p><ol><li><strong>Number of snakes</strong>: Followed by snake positions, each represented by the head and tail coordinates.</li><li><strong>Number of ladders</strong>: Followed by ladder positions, each represented by start and end coordinates.</li><li><strong>Number of players</strong>: Followed by player names.</li></ol><h4>Example Input:</h4><pre>3<br>14 7<br>98 79<br>63 60<br>2<br>8 32<br>36 44<br>3<br>Alice<br>Bob<br>Charlie</pre><p>In this example:</p><ul><li>3 snakes: head at 14, 98, 63 (tails at 7, 79, 60).</li><li>2 ladders: start at 8, 36 (ends at 32, 44).</li><li>3 players: Alice, Bob, and Charlie.</li></ul><h3>Game Rules:</h3><ul><li>Each player rolls a dice (range: 1–6) in turn.</li><li>Players move forward by the value of the dice.</li><li>If a player lands on the head of a snake, they slide down to its tail.</li><li>If a player lands at the base of a ladder, they climb up to its top.</li><li>If a dice roll moves a player beyond 100, they stay in their current position.</li><li>The first player to reach exactly 100 wins.</li></ul><h3>Solution Approach</h3><h4>Defining Core Entities</h4><p>To model the game, we need to represent the following:</p><ol><li><strong>Board</strong>: This contains the positions of snakes and ladders.</li><li><strong>Player</strong>: This stores each player’s name and their current position.</li><li><strong>Game</strong>: This handles the game mechanics, including dice rolls and player turns.</li></ol><h3>Logic Flow</h3><h4>1. Board Setup:</h4><ul><li>Snakes and ladders are defined by a start and an end position.</li><li>We’ll use maps in Go to represent these snakes and ladders, making it easy to check whether a player lands on a snake or ladder.</li></ul><h4>2. Player Movement:</h4><ul><li>For each turn, the player rolls a dice, moves forward, and checks if they landed on a snake or ladder. If so, their position is adjusted accordingly.</li></ul><h4>3. Dice Roll:</h4><ul><li>A random dice roll generates a number between 1 and 6. The player’s position is updated based on the dice value.</li></ul><h4>4. Winning Condition:</h4><ul><li>A player wins by landing exactly on the 100th cell. If the dice roll would move the player beyond 100, they remain in their current position.</li></ul><h3>Let’s Code the Solution</h3><h3>Step 1: Define the Structures</h3><p>We’ll start by defining the Ladder , Snakes, Player and Gamestructs.</p><pre>package models<br><br>type Ladders struct {<br> Start int<br> End   int<br>}<br><br>func CreateLadder(start, end int) Ladders {<br> return Ladders{<br>  Start: start,<br>  End:   end,<br> }<br>}</pre><p>The Ladder struct keeps track of the ladders configured in the game</p><pre>package models<br><br>type Snakes struct {<br> Start int<br> End   int<br>}<br><br>func CreateSnakes(start, end int) Snakes {<br> return Snakes{<br>  Start: start,<br>  End:   end,<br> }<br>}</pre><p>The Snake struct keeps track of the ladders configured in the game</p><pre>package models<br><br>import &quot;github.com/google/uuid&quot;<br><br>type Player struct {<br> Name string<br> Id   string<br>}<br><br>func NewPlayer(name string) Player {<br> return Player{<br>  Name: name,<br>  Id:   uuid.New().String(),<br> }<br>}</pre><p>The Player struct keeps track of each player&#39;s name and position on the board</p><pre>package models<br><br>type SnakeLadderBoard struct {<br> Size            int<br> Ladders         []Ladders<br> Snakes          []Snakes<br> PlayerPositions map[string]int<br>}<br><br>func NewSnakeLadderBoard(size int) SnakeLadderBoard {<br> return SnakeLadderBoard{<br>  Size:            size,<br>  Ladders:         make([]Ladders, 0),<br>  Snakes:          make([]Snakes, 0),<br>  PlayerPositions: make(map[string]int),<br> }<br>}</pre><p>The SnakeLadderBoard struct stores information about the snakes, ladders, and players.</p><h3>Step 2: Initialize the Game</h3><p>Next, we define a method to initialize the game with snakes, ladders, and players.</p><pre>type SnakeLadderService struct {<br> NoOfDice        int<br> NumberOfPlayers int<br> Board           models.SnakeLadderBoard<br> Players         *list.List<br>}<br><br>func NewSnakeLadderService(boardSize, noOfDice int) SnakeLadderService {<br> return SnakeLadderService{<br>  NoOfDice: noOfDice,<br>  Board:    models.NewSnakeLadderBoard(boardSize),<br> }<br>}<br><br>func (s *SnakeLadderService) SetPlayers(players []models.Player) {<br> playerList := list.New()<br> for _, v := range players {<br>  playerList.PushBack(v)<br> }<br> s.Players = playerList<br> s.NumberOfPlayers = playerList.Len()<br><br> playerPositions := make(map[string]int, 0)<br> for _, v := range players {<br>  playerPositions[v.Id] = 0<br> }<br> s.Board.PlayerPositions = playerPositions<br>}<br><br>func (s *SnakeLadderService) SetSnakes(snakes []models.Snakes) {<br> s.Board.Snakes = snakes<br>}<br><br>func (s *SnakeLadderService) SetLadders(ladders []models.Ladders) {<br> s.Board.Ladders = ladders<br>}</pre><p>Here, we initialize a new SnakeLadderGame instance with the specified number of players, snakes, and ladders.</p><h3>Step 3: Implement the Dice Roll and Player Movement</h3><p>We’ll now implement a function to simulate the dice roll and handle player movement, including interactions with snakes and ladders.</p><pre>func (s *SnakeLadderService) roll() int {<br> return rand.Intn(6*s.NoOfDice) + 1<br>}<br><br>func (s *SnakeLadderService) movePlayer(player models.Player, position int) {<br> oldPosition := s.Board.PlayerPositions[player.Id]<br> newPosition := oldPosition + position<br><br> if newPosition &gt; s.Board.Size {<br>  newPosition = oldPosition<br> } else {<br>  newPosition = s.getPositionAfterTurn(newPosition)<br> }<br><br> s.Board.PlayerPositions[player.Id] = newPosition<br> fmt.Println(player.Name, &quot;rolled a&quot;, position, &quot;and moved from&quot;, oldPosition, &quot;to&quot;, newPosition)<br>}<br><br>func (s *SnakeLadderService) getPositionAfterTurn(newPosition int) int {<br> var previousPosition int<br><br> if newPosition != previousPosition {<br>  previousPosition = newPosition<br>  for _, snake := range s.Board.Snakes {<br>   if snake.Start == newPosition {<br>    newPosition = snake.End<br>   }<br>  }<br><br>  for _, ladder := range s.Board.Ladders {<br>   if ladder.Start == newPosition {<br>    newPosition = ladder.End<br>   }<br>  }<br> }<br> return previousPosition<br>}<br><br>func (s *SnakeLadderService) hasPlayerWon(player models.Player) bool {<br> playerPosition := s.Board.PlayerPositions[player.Id]<br> winningPosition := s.Board.Size<br><br> return playerPosition == winningPosition<br>}<br><br>func (s *SnakeLadderService) isGameCompleted() bool {<br> currentPlayers := s.Players.Len()<br> return currentPlayers &lt; s.NumberOfPlayers<br>}</pre><ul><li>rollDice() function generates a random number between 1 and <em>number of dices * 6</em></li><li>movePlayer() function moves the player forward and checks if they landed on a snake or ladder.</li><li>hasPlayerWon() function checks if the current user has completed the game</li><li>isGameCompleted() function checks if the game is completed or not.</li></ul><h3>Step 4: Game Loop</h3><p>Finally, we’ll implement the game loop that keeps the game running until a player wins.</p><pre><br>func (s *SnakeLadderService) StartGame() {<br> for !s.isGameCompleted() {<br>  diceRoll := s.roll()<br>  current := s.Players.Front()<br>  currentPlayer := current.Value.(models.Player)<br>  s.movePlayer(currentPlayer, diceRoll)<br>  if s.hasPlayerWon(currentPlayer) {<br>   fmt.Println(&quot;Player&quot;, currentPlayer.Name, &quot;won the game&quot;)<br>   s.Players.Remove(current)<br>  } else {<br>   s.Players.Remove(current)<br>   s.Players.PushBack(currentPlayer)<br>  }<br> }<br>}</pre><p>This loop continuously cycles through each player, moving them on the board until a player wins.</p><h3>Step 5: Example Usage</h3><p>Now, let’s set up the game with snakes, ladders, and players, and start the game.</p><pre>package main<br><br>import (<br> &quot;github.com/Vishalj32/system-design/low-level-designs/snakes-n-ladders/models&quot;<br> &quot;github.com/Vishalj32/system-design/low-level-designs/snakes-n-ladders/service&quot;<br>)<br><br>func main() {<br><br> snakeLadderService := service.NewSnakeLadderService(100, 1)<br> var players []models.Player<br> players = append(players, models.NewPlayer(&quot;John&quot;), models.NewPlayer(&quot;Jane&quot;))<br><br> var snakes []models.Snakes<br> snakes = append(snakes, models.CreateSnakes(99, 25), models.CreateSnakes(88, 54), models.CreateSnakes(29, 10))<br><br> var ladders []models.Ladders<br> ladders = append(ladders, models.CreateLadder(14, 28), models.CreateLadder(55, 97), models.CreateLadder(42, 78), models.CreateLadder(52, 92))<br><br> snakeLadderService.SetPlayers(players)<br> snakeLadderService.SetLadders(ladders)<br> snakeLadderService.SetSnakes(snakes)<br><br> snakeLadderService.StartGame()<br>}</pre><p>In this article, we built a <strong>LLD implementation of</strong> <strong>Snake and Ladder game</strong> using Go. We used maps to represent the snakes and ladders and added logic for dice rolls, player movements, and winning conditions. The game can be easily customized by adding more players, snakes, ladders, or even changing the board size.</p><p>The above implementation can be found in my github repository</p><p><a href="https://github.com/Vishalj32/system-design/tree/main/low-level-designs/snakes-n-ladders">system-design/low-level-designs/snakes-n-ladders at main · Vishalj32/system-design</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5f34887a14b" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/lld-system-design-series-snake-and-ladders-in-go-a5f34887a14b">LLD System Design Series: Snake And Ladders in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLD System Design Series: Building an Expense Sharing Application in Go]]></title>
            <link>https://towardsdev.com/lld-system-design-series-day-1-building-an-expense-sharing-application-in-go-86b14a7f89ac?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/86b14a7f89ac</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 11:27:15 GMT</pubDate>
            <atom:updated>2024-09-30T09:14:06.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mYLJ1FUB_RXKMp4u2w7XYg.png" /></figure><p>Splitting expenses can get messy, especially when you live with multiple people. Whether it’s splitting the rent, utility bills, or any group expense, manually keeping track of who owes whom is a hassle. So why not build an application that handles this for you?</p><p>In this article, we’ll walk through the process of creating an <strong>Expense Sharing Application</strong> using <strong>Go</strong>. We’ll cover how to design the system, break down the logic, and implement the solution. By the end of this article, you’ll have a fully functional expense tracker.</p><h4>LLD Scenario</h4><pre>Here’s a reformulated version of the expense-sharing application problem, made more intuitive and structured:<br><br>---<br><br>### Expense Sharing Application<br><br>#### Overview:<br>You’re tasked with building an expense-sharing application that helps users track shared expenses and balances between participants. Users should be able to add expenses, split costs between individuals, and view their balances with others. The app must efficiently manage transactions and keep a running balance of who owes whom, making the settlement process simple and transparent.<br><br>---<br><br>### Scenario:<br><br>Imagine you live with 3 friends and frequently share expenses like rent, groceries, or outings. You pay some expenses yourself, and others are paid by your friends. You need an application that allows you to track these expenses and split the amounts fairly between all users.<br><br>---<br><br>### Functional Requirements:<br><br>#### Users:<br><br>Each user has the following properties:<br>- **UserId** (e.g., u1)<br>- **Name** (e.g., User1)<br>- **Email**<br>- **Mobile Number**<br><br>#### Expense Types:<br><br>1. **Equal Split**: The total amount is divided equally between all users.  <br>   Example: If User1 pays ₹1000 for an electricity bill split among 4 people, each person owes ₹250.<br><br>2. **Exact Split**: Each user owes a specific amount.  <br>   Example: User1 buys items for User2 and User3. User2 owes ₹370, and User3 owes ₹880 from a total expense of ₹1250.<br><br>3. **Percent Split**: The amount is split based on percentage shares for each participant.  <br>   Example: User4 pays ₹1200, and the split is 40% for User1 and 20% for the others.<br><br>#### Key Features:<br><br>1. **Add Expense**:<br>   - Input Format:  <br>     `EXPENSE &lt;payer-user-id&gt; &lt;amount&gt; &lt;number-of-users&gt; &lt;space-separated-list-of-users&gt; &lt;EQUAL/EXACT/PERCENT&gt; &lt;optional-amounts-or-percentages&gt;`<br>   - Examples:<br>     - Equal Split: `EXPENSE u1 1000 4 u1 u2 u3 u4 EQUAL`<br>     - Exact Split: `EXPENSE u1 1250 3 u2 u3 EXACT 370 880`<br>     - Percent Split: `EXPENSE u4 1200 4 u1 u2 u3 u4 PERCENT 40 20 20 20`<br><br>2. **Show Balances**:<br>   - Displays outstanding balances between users.<br>   - If balances exist, show them in the format:  <br>     `&lt;user-x-id&gt; owes &lt;user-y-id&gt;: &lt;amount&gt;`<br>   - Input format: <br>     - Show all balances: `SHOW`<br>     - Show balances for a single user: `SHOW &lt;user-id&gt;`<br>   - If no balances exist for the user, return &quot;No balances.&quot;<br><br>3. **Validation**:<br>   - For **Percent Split**, verify that the total percentage is exactly 100%.<br>   - For **Exact Split**, ensure the sum of individual amounts matches the total expense.<br><br>4. **Rounding**:<br>   - Amounts should be rounded to two decimal places for fairness in splits.<br><br>---<br><br>### Example Scenarios:<br><br>1. **Electricity Bill**:  <br>   Input: `EXPENSE u1 1000 4 u1 u2 u3 u4 EQUAL`  <br>   - Each user owes ₹250 to User1.<br><br>2. **Flipkart Purchase**:  <br>   Input: `EXPENSE u1 1250 2 u2 u3 EXACT 370 880`  <br>   - User2 owes ₹370, and User3 owes ₹880 to User1.<br><br>3. **Dinner Expense**:  <br>   Input: `EXPENSE u4 1200 4 u1 u2 u3 u4 PERCENT 40 20 20 20`  <br>   - User1 owes ₹480, User2 and User3 each owe ₹240 to User4.<br><br>---<br><br>### Optional Features:<br><br>1. **Expense Name and Notes**:  <br>   Add descriptive details to each expense like the name of the expense or any relevant notes.<br><br>2. **Share-Based Splitting**:  <br>   Users can split costs based on the number of shares each participant contributes, such as when someone pays for multiple people.  <br>   Example: `EXPENSE u4 1200 4 u1 u2 u3 u4 SHARE 2 1 1 1`<br><br>3. **Passbook View**:  <br>   Show a detailed list of all transactions a user is involved in.<br><br>4. **Simplify Balances**:  <br>   If there are circular debts, simplify them. For example, if User1 owes User2 ₹250, and User2 owes User3 ₹200, simplify it so User1 owes ₹50 to User2 and ₹200 to User3.</pre><h4>Solution</h4><p>Definig the Core Entities</p><p>The core of the application will include:</p><ol><li>User: Each user will have a unique ID, a name, an email, and a phone number.</li><li>Expense: Represents an expense with details like the payer, total amount, the list of users involved, and how the expense was split (EQUAL, EXACT, or PERCENT).</li><li>ExpenseManager: A central manager to handle users, their balances, and expenses.</li></ol><h3>Logic Flow</h3><h4>1. Adding an Expense:</h4><p>When an expense is added, the application will split the amount based on the chosen method (EQUAL, EXACT, or PERCENT). The balances between users will be updated accordingly.</p><h4>2. Displaying Balances:</h4><p>When requested, the app will display how much each user owes or is owed by others. This will involve looping through each user’s balances and printing out non-zero balances.</p><h3>Input and Output</h3><ul><li><strong>Input Format</strong>: The input will consist of commands for adding an expense or displaying balances.</li><li><strong>Add Expense</strong>: EXPENSE &lt;user-id-who-paid&gt; &lt;total-amount&gt; &lt;no-of-users&gt; &lt;user-ids-involved&gt; &lt;EQUAL/EXACT/PERCENT&gt; &lt;amounts/percentages&gt;</li><li><strong>Show Balances for All Users</strong>: SHOW</li><li><strong>Show Balances for a Specific User</strong>: SHOW &lt;user-id&gt;</li><li><strong>Output Format</strong>: Balances will be displayed as: &lt;user-id-x&gt; owes &lt;user-id-y&gt;: &lt;amount&gt;</li></ul><h3>Let’s Code the Solution</h3><h4>Step 1: Define the User, Expense structures</h4><p>We start by defining the User and Balance structs in Go.</p><pre>package models<br><br>// User represents a user in the system<br>type User struct {<br> ID    string<br> Name  string<br> Email string<br> Phone string<br>}</pre><p>The User struct contains basic details about each user.</p><h3>Step 2: Add Expense Logic</h3><p>Next, we define the logic for adding an expense. We’ll handle different cases for splitting the amount: equally, by exact amounts, or by percentages.</p><pre>package models<br><br>// ExpenseType is the type of the expense (EQUAL, EXACT, PERCENT)<br>type ExpenseType string<br><br>const (<br> EQUAL   ExpenseType = &quot;EQUAL&quot;<br> EXACT   ExpenseType = &quot;EXACT&quot;<br> PERCENT ExpenseType = &quot;PERCENT&quot;<br>)<br><br>// Expense represents an expense in the application<br>type Expense struct {<br> PayerId       string<br> Amount        float64<br> UsersInvolved []string<br> Splits        []float64<br> ExpenseType   ExpenseType<br>}</pre><p>The Expense struct holds details about who paid, how much was paid, how the amount is split, and which users are involved.</p><h3>Step 3: Implement the Main Logic</h3><p>Let’s add the core logic to split expenses and maintain balances between users.</p><pre>package models<br><br>import (<br> &quot;fmt&quot;<br> &quot;math&quot;<br>)<br><br>// ExpenseManager handles all the users, balances and expenses<br>type ExpenseManager struct {<br> Users    map[string]*User<br> Balances map[string]map[string]float64<br>}<br><br>// NewExpenseManager creates a new instance of ExpenseManager<br>func NewExpenseManager() *ExpenseManager {<br> return &amp;ExpenseManager{<br>  Users:    make(map[string]*User, 0),<br>  Balances: make(map[string]map[string]float64),<br> }<br>}<br><br>// AddUser adds a new user<br>func (em *ExpenseManager) AddUser(user *User) {<br> em.Users[user.ID] = user<br> em.Balances[user.ID] = make(map[string]float64)<br>}<br><br>func (em *ExpenseManager) updateBalance(payerId, userId string, amount float64) {<br> em.Balances[userId][payerId] += amount<br>}<br><br>// splitEqual handles EQUAL split of expenses<br>func (em *ExpenseManager) splitEqual(expense *Expense) {<br> totalUsers := len(expense.UsersInvolved)<br> equalSplit := math.Round((expense.Amount/float64(totalUsers))*100) / 100<br><br> for _, userId := range expense.UsersInvolved {<br>  if userId == expense.PayerId {<br>   em.updateBalance(expense.PayerId, userId, equalSplit)<br>  }<br> }<br>}<br><br>// splitExact handles EXACT split of expense<br>func (em *ExpenseManager) splitExact(expense *Expense) {<br> sum := 0.0<br> for _, split := range expense.Splits {<br>  sum += split<br> }<br><br> if math.Round(sum*100)/100 != expense.Amount {<br>  fmt.Println(&quot;Error: Exact split amounts do not match the total amount&quot;)<br>  return<br> }<br><br> for idx, userId := range expense.UsersInvolved {<br>  if userId != expense.PayerId {<br>   em.updateBalance(expense.PayerId, userId, expense.Splits[idx])<br>  }<br> }<br>}<br><br>// splitPercent handles PERCENT split of expense<br>func (em *ExpenseManager) splitPercent(expense *Expense) {<br> totalPercent := 0.0<br> for _, percent := range expense.Splits {<br>  totalPercent += percent<br> }<br><br> if math.Round(totalPercent*100)/100 != 100.0 {<br>  fmt.Println(&quot;Error: Total percentage is not 100&quot;)<br>  return<br> }<br><br> for idx, userId := range expense.UsersInvolved {<br>  if userId != expense.PayerId {<br>   share := math.Round((expense.Amount*(expense.Splits[idx]/100))*100) / 100<br>   em.updateBalance(expense.PayerId, userId, share)<br>  }<br> }<br><br>}<br><br>// AddExpense adds a new expense to system<br>func (em *ExpenseManager) AddExpense(expense *Expense) {<br> switch expense.ExpenseType {<br> case EQUAL:<br>  {<br>   em.splitEqual(expense)<br>  }<br> case EXACT:<br>  {<br>   em.splitExact(expense)<br>  }<br> case PERCENT:<br>  {<br>   em.splitPercent(expense)<br>  }<br> }<br>}<br><br>// ShowBalance displays balance of the specific userID<br>func (em *ExpenseManager) ShowBalance(userId string) {<br> found := false<br> for otherUserid, balance := range em.Balances[userId] {<br>  if balance != 0 {<br>   if balance &gt; 0 {<br>    fmt.Printf(&quot;%s owes %s: %.2f\n&quot;, userId, otherUserid, balance)<br>   } else {<br>    fmt.Printf(&quot;%s owes %s: %.2f\n&quot;, otherUserid, userId, -balance)<br>   }<br>   found = true<br>  }<br> }<br><br> if !found {<br>  fmt.Println(&quot;No Balances&quot;)<br> }<br>}<br><br>// ShowAllBalances displays all the user balance in the system<br>func (em *ExpenseManager) ShowAllBalances() {<br> for userId, userBalances := range em.Balances {<br>  for otherUserId, balance := range userBalances {<br>   if balance &gt; 0 {<br>    fmt.Printf(&quot;%s owes %s: %.2f\n&quot;, userId, otherUserId, balance)<br>   } else {<br>    fmt.Printf(&quot;%s owes %s: %.2f\n&quot;, otherUserId, userId, -balance)<br>   }<br>  }<br> }<br>}</pre><h3>Step 4: Example Usage</h3><p>Now, we will demonstrate how this works with some example inputs in the main function:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br><br> &quot;github.com/Vishalj32/system-design/low-level-designs/splitwise/models&quot;<br>)<br><br>func main() {<br> // Initialize the expense manager<br> em := models.NewExpenseManager()<br><br> // Add users<br> em.AddUser(&amp;models.User{ID: &quot;u1&quot;, Name: &quot;User1&quot;, Email: &quot;user1@example.com&quot;, Phone: &quot;1234567890&quot;})<br> em.AddUser(&amp;models.User{ID: &quot;u2&quot;, Name: &quot;User2&quot;, Email: &quot;user2@example.com&quot;, Phone: &quot;1234567891&quot;})<br> em.AddUser(&amp;models.User{ID: &quot;u3&quot;, Name: &quot;User3&quot;, Email: &quot;user3@example.com&quot;, Phone: &quot;1234567892&quot;})<br> em.AddUser(&amp;models.User{ID: &quot;u4&quot;, Name: &quot;User4&quot;, Email: &quot;user4@example.com&quot;, Phone: &quot;1234567893&quot;})<br><br> // Add expenses<br> em.AddExpense(&amp;models.Expense{<br>  PayerId:       &quot;u1&quot;,<br>  Amount:        1000,<br>  UsersInvolved: []string{&quot;u1&quot;, &quot;u2&quot;, &quot;u3&quot;, &quot;u4&quot;},<br>  ExpenseType:   models.EQUAL,<br> })<br><br> em.AddExpense(&amp;models.Expense{<br>  PayerId:       &quot;u1&quot;,<br>  Amount:        1250,<br>  UsersInvolved: []string{&quot;u2&quot;, &quot;u3&quot;},<br>  ExpenseType:   models.EXACT,<br>  Splits:        []float64{370, 880},<br> })<br><br> em.AddExpense(&amp;models.Expense{<br>  PayerId:       &quot;u4&quot;,<br>  Amount:        1200,<br>  UsersInvolved: []string{&quot;u1&quot;, &quot;u2&quot;, &quot;u3&quot;, &quot;u4&quot;},<br>  ExpenseType:   models.PERCENT,<br>  Splits:        []float64{40, 20, 20, 20},<br> })<br><br> // Show balances<br> fmt.Println(&quot;Balances for u1:&quot;)<br> em.ShowBalance(&quot;u1&quot;)<br><br> fmt.Println(&quot;\nAll balances:&quot;)<br> em.ShowAllBalances()<br>}</pre><h3>Conclusion</h3><p>In this article, we walked through building a simple yet powerful expense-sharing application using <strong>Go</strong>. We defined core entities like User, Expense, and ExpenseManager and implemented the logic for splitting expenses equally, by exact amounts, and by percentages.</p><blockquote>The above code can be found in my personal <a href="https://github.com/Vishalj32/system-design/tree/main">github</a> repository</blockquote><p><a href="https://github.com/Vishalj32/system-design/tree/main">https://github.com/Vishalj32/system-design/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86b14a7f89ac" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/lld-system-design-series-day-1-building-an-expense-sharing-application-in-go-86b14a7f89ac">LLD System Design Series: Building an Expense Sharing Application in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring of Ktor Applications with Prometheus and Grafana]]></title>
            <link>https://towardsdev.com/advanced-monitoring-of-ktor-applications-with-prometheus-and-grafana-a495605e0443?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/a495605e0443</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 11:00:40 GMT</pubDate>
            <atom:updated>2024-03-07T21:49:11.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhkTYWNW4L4lAuOJv7TpTA.png" /><figcaption>Dashboard</figcaption></figure><p>Monitoring and observability are critical components of modern web application development, allowing teams to detect issues before they affect users and make informed decisions about optimizstions. For applications built with Ktor, a lightweight Kotlin framework, integrating with robust tools like Prometheus for monitoring and Grafana for visualization provides a deep insight into the application’s performance and health. This article dives into a more detailed approach to setting up and utilizing Prometheus and Grafana for advanced monitoring of Ktor applications.</p><h3>Why Prometheus and Grafana?</h3><p><strong>Prometheus:</strong> is a powerful open-source monitoring solution that collects and stores its metrics as time series data. This data can then be queried and analyzed with its query language, PromQL. Prometheus is designed for reliability and simplicity, offering precise insight into applications and infrastructure without the overhead of complex setup procedures.</p><p><strong>Grafana:</strong> complements Prometheus by providing a powerful and flexible dashboarding tool for visualizing time series data. With Grafana, developers and operations teams can create comprehensive dashboards that offer real-time insights into application metrics, system performance, and operational health.</p><h3>Step-by-Step Integration of Prometheus with Ktor</h3><h4>Step 1: Setting Up the Environment</h4><p>Before diving into the code, ensure that you have a Ktor application running. If you’re new to Ktor, you can quickly start a project using the <a href="https://start.ktor.io/">Ktor Project Generator</a> or by following the official <a href="https://ktor.io/docs/creating-http-apis.html">Ktor documentation</a>.</p><h3>Step 2: Adding Necessary Dependencies</h3><p>To begin, add the Prometheus and Ktor metrics dependencies to your project&#39;s build.gradle.kts file:</p><pre>dependencies {<br>    implementation(&quot;io.ktor:ktor-server-core:&lt;ktor_version&gt;&quot;)<br>    implementation(&quot;io.ktor:ktor-server-netty:&lt;ktor_version&gt;&quot;)<br>    implementation(&quot;io.ktor:ktor-metrics-micrometer:&lt;ktor_version&gt;&quot;)<br>    implementation(&quot;io.micrometer:micrometer-registry-prometheus:&lt;micrometer_version&gt;&quot;)<br>}</pre><p>Replace &lt;ktor_version&gt; and &lt;micrometer_version&gt; with the latest versions available for these libraries.</p><h3>Step 3: Configuring Prometheus Metrics in Ktor</h3><p>Integration begins in the application’s main module, where you configure Ktor to expose a metrics endpoint that Prometheus can scrape:</p><pre>import io.ktor.server.application.*<br>import io.ktor.server.routing.*<br>import io.ktor.server.response.*<br>import io.ktor.metrics.micrometer.*<br>import io.micrometer.core.instrument.binder.jvm.*<br>import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics<br>import io.micrometer.core.instrument.binder.system.ProcessorMetrics<br>import io.micrometer.core.instrument.binder.system.UptimeMetrics<br>import io.micrometer.core.instrument.distribution.DistributionStatisticConfig<br>import io.micrometer.prometheus.PrometheusConfig<br>import io.micrometer.prometheus.PrometheusMeterRegistry<br>import io.micrometer.prometheus.PrometheusConfig<br>import java.time.Duration<br><br>fun Application.module(testing: Boolean = false) {<br>    install(MicrometerMetrics) {<br>       registry = appMicrometerRegistry<br>        distributionStatisticConfig = DistributionStatisticConfig.Builder()<br>            .percentilesHistogram(true)<br>            .maximumExpectedValue(Duration.ofSeconds(20).toNanos().toDouble())<br>            .serviceLevelObjectives(<br>                Duration.ofMillis(100).toNanos().toDouble(),<br>                Duration.ofMillis(500).toNanos().toDouble()<br>            ).build()<br>        meterBinders = listOf(<br>            JvmMemoryMetrics(),<br>            JvmGcMetrics(),<br>            ProcessorMetrics(),<br>            JvmThreadMetrics(),<br>            ClassLoaderMetrics(),<br>            UptimeMetrics(),<br>            JvmCompilationMetrics(),<br>            FileDescriptorMetrics(),<br>            JvmHeapPressureMetrics(),<br>        )<br>    }<br>    routing {<br>        get(&quot;/metrics&quot;) { call.respond(appMicrometerRegistry.scrape()) }<br>    }<br>}</pre><p>This setup does two key things:</p><ul><li>Installs the MicrometerMetrics feature and configures it with a Prometheus meter registry.</li><li>After installing MicrometerMetrics, you need to create a <a href="https://micrometer.io/docs/concepts#_registry">registry for your monitoring system</a> and assign it to the registry property.</li><li>The MicrometerMetrics plugin provides various configuration options that can be accessed using <a href="https://api.ktor.io/ktor-server/ktor-server-plugins/ktor-server-metrics-micrometer/io.ktor.server.metrics.micrometer/-micrometer-metrics-config/index.html">MicrometerMetricsConfig</a>.</li><li>You configure <a href="https://micrometer.io/docs/concepts#_configuring_distribution_statistics">distribution statistics</a> using the distributionStatisticConfig property.</li><li>In addition to <a href="https://ktor.io/docs/micrometer-metrics.html#ktor_metrics">HTTP metrics</a>, Ktor exposes a set of metrics for <a href="https://micrometer.io/docs/ref/jvm">monitoring the JVM</a>. You can customize a list of these metrics using the meterBinders property.</li><li>Defines a /metrics endpoint that returns the current state of metrics collected by Prometheus in a format it can scrape.</li></ul><h3>Step 4: Configuring Prometheus</h3><p>On the Prometheus side, you need to configure it to know where to find your Ktor application metrics. Edit the Prometheus configuration file (prometheus.yml) to include your application as a target:</p><pre>scrape_configs:<br>  - job_name: &#39;ktor_application&#39;<br>    static_configs:<br>      - targets: [&#39;localhost:8080&#39;]<br>    metrics_path: &#39;/metrics&#39;<br>    scrape_interval: 5s</pre><p>This configuration tells Prometheus to scrape the /metrics endpoint of your Ktor application running on localhost:8080 every 5 seconds.</p><h3>Step 5: Running Prometheus and Grafana</h3><p>With Prometheus configured, you can run it using the official Docker image or a binary distribution. Similarly, Grafana can be started using its Docker image or a direct installation. Once both services are up, proceed to Grafana’s web interface to configure Prometheus as a data source and start creating dashboards.</p><h3>Step 6: Visualizing Data in Grafana</h3><ul><li>Navigate to “Create &gt; Dashboard” and click “Add new panel.”</li><li>From the query tab, select the Prometheus data source you just added.</li><li>You can then enter Prometheus queries to visualize different metrics. For example, <strong>http_requests_total</strong> can show you the total number of HTTP requests your application has handled.</li><li>After configuring your queries and panel settings, save the panel to the dashboard.</li></ul><p>Repeat the process to add more panels as needed, experimenting with different queries and visualizations to get a comprehensive view of your Ktor application’s performance and health.</p><blockquote>Note: Preconfigured dashboards can also be used for monitoring, example dashboard can be viewed <a href="https://grafana.com/grafana/dashboards/4701-jvm-micrometer/">here</a>.</blockquote><h4>Get the Dashboard’s up!!</h4><p>At this stage, the major tasks have been completed, but there are still a few remaining items on the agenda. Our first priority is to reconstruct the backend Docker image and initiate Docker compose up. Upon completion of these tasks, you should be able to access the Grafana control panel via the URL <a href="http://localhost:3000/">http://localhost:3000</a>.</p><p>Upon accessing Grafana, you will be prompted to enter a username and password. You can use the default credentials admin/admin to log in. Once logged in, you will need to establish a datasource (linked to the Prometheus instance) and configure a dashboard (a collection of graphs for data visualization).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bk3D8OKMTPD8vCnwrvgNA.png" /><figcaption>Datasource</figcaption></figure><p>For setting up the Prometheus datasource, simply replicate the configuration as displayed in the preceding image.</p><blockquote>Note: Ensure that you use <a href="http://prometheus:9090/">http://prometheus:9090</a> and not the suggested <a href="http://localhost:9090/">http://localhost:9090</a>.</blockquote><p>Remember to generate some requests to your backend instance to observe the graphs in action. You can utilize the <a href="https://github.com/Vishalj32/ktor-profiling/blob/main/Ktor-Profiling-Demo.postman_collection.json">postman</a> collection provided in the repository.</p><p>To create a Grafana dashboard, navigate to the import option in the menu, choose “import dashboard” and add the dashboard ID for a specific dashboard, in our case <a href="https://grafana.com/grafana/dashboards/4701-jvm-micrometer/">JVM (Micrometer) Dashboard </a>. Grafana will prompt you to name the dashboard and assign a datasource (the one established in the previous step). After saving, the graphs should become visible on your screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhkTYWNW4L4lAuOJv7TpTA.png" /><figcaption>Dashboard in action</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjvP6MpK1jTk0fLczSvr5g.png" /><figcaption>Dashboard in action</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KjOmuWC7aHwioNStwUMt0g.png" /><figcaption>Dashboard in action</figcaption></figure><h3>Leveraging Advanced Features</h3><p>While the basic setup provides significant insight, both Prometheus and Grafana offer advanced features worth exploring:</p><ul><li><strong>Prometheus Alerting:</strong> Define alert rules in Prometheus to send notifications via email, Slack, or other channels when certain conditions are met, such as an unusually high error rate.</li><li><strong>Grafana Alerts:</strong> Grafana also provides alerting functionality, with the added benefit of being able to trigger alerts based on the visualizations you create.</li><li><strong>Custom Metrics:</strong> Beyond the default metrics, consider instrumenting your Ktor application with custom metrics that are specific to your domain or business logic. This might include things like transaction volumes, processing times for specific tasks, or custom error rates.</li></ul><h3>Conclusion</h3><p>Integrating Prometheus and Grafana with your Ktor application provides a sophisticated monitoring solution that can greatly enhance your ability to observe, diagnose, and optimize your application. By following the steps outlined in this guide and exploring the advanced features of these tools, you can establish a robust monitoring framework that supports the reliability and performance of your services.</p><p>Project and all the files mentioned above are available in my GitHub repository. Please feel free to check it out and in case of any issues please do raise it on the same.</p><p><a href="https://github.com/Vishalj32/ktor-profiling">GitHub - Vishalj32/ktor-profiling</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a495605e0443" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/advanced-monitoring-of-ktor-applications-with-prometheus-and-grafana-a495605e0443">Monitoring of Ktor Applications with Prometheus and Grafana</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Your Database production ready]]></title>
            <link>https://towardsdev.com/getting-your-database-production-ready-ffb0f68ede00?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffb0f68ede00</guid>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 05:45:12 GMT</pubDate>
            <atom:updated>2024-03-02T08:10:38.870Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Your Database ready for scale</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*tBoaCAG1fr9Py5PqHp2iKw.jpeg" /></figure><h3>Why Database is the Weakest Link</h3><p>The term “weakest link” when referring to a database in the context of an application typically relates to the fact that the database often represents a critical and vulnerable component in the overall system. Several reasons contribute to this characterisation:</p><ol><li><strong>Data Integrity and Security:</strong> Databases store and manage sensitive and critical data. If the database lacks proper security measures, it becomes a potential target for unauthorised access, data breaches, or data manipulation. Ensuring data integrity and confidentiality is crucial, and any compromise in these areas can have severe consequences for the entire application.</li><li><strong>Single Point of Failure:</strong> In many applications, the database serves as a single point of failure. If the database goes down or experiences issues, it can render the entire application unusable. This dependency on a single component makes the database a critical element that needs to be robust and highly available.</li><li><strong>Performance Bottlenecks:</strong> Inefficient database design or poorly optimized queries can lead to performance bottlenecks. Slow database response times can degrade the overall application performance, affecting user experience and system responsiveness.</li><li><strong>Scalability Challenges:</strong> As an application grows, the database needs to handle an increasing amount of data and user requests. Scaling a database can be challenging, and issues related to scalability might emerge as a bottleneck, impacting the application’s ability to handle a growing user base or increased data volume.</li><li><strong>Lack of Regular Maintenance:</strong> Neglecting routine database maintenance, such as backups, updates, and monitoring, can increase the risk of data loss, security vulnerabilities, and performance issues.</li><li><strong>Dependency on Database Management Systems (DBMS):</strong> The choice of the database management system (e.g., MySQL, PostgreSQL, MongoDB) can significantly impact an application. Changes in the underlying DBMS or its version may require careful planning and testing to ensure compatibility and prevent disruptions.</li></ol><h3>Understanding Explain and query plans</h3><p>Analyzing and explaining a query in MariaDB involves several steps that help you understand how the database engine processes a specific query. This can be crucial for optimizing performance and identifying potential bottlenecks. Here’s a step-by-step guide:</p><p><strong>Use the EXPLAIN Statement</strong>:</p><ul><li>The <strong>EXPLAIN</strong> statement is used in MariaDB to get information about how the database engine executes a query.</li><li>Syntax: <strong>EXPLAIN [your SQL query];</strong></li><li>Example: <strong>EXPLAIN SELECT * FROM users WHERE id = 1;</strong></li></ul><p><strong>Understanding EXPLAIN Output</strong>:</p><p>The <strong>EXPLAIN</strong> statement returns several columns, each providing valuable insights. Key columns include:</p><ul><li><strong>id</strong>: The identifier for each select in a query.</li><li><strong>select_type</strong>: The type of SELECT (e.g., SIMPLE, PRIMARY, SUBQUERY).</li><li><strong>table</strong>: The table to which the row of output refers.</li><li><strong>type</strong>: The join type (e.g., ALL, index, range).</li><li><strong>possible_keys</strong>: Which indexes could be used to find rows in the table?</li><li><strong>key</strong>: The index chosen by the optimizer.</li><li><strong>rows</strong>: Estimated number of rows to be examined.</li><li><strong>Extra</strong>: Additional details about how MariaDB resolves the query.</li></ul><p><strong>Analyzing the Results</strong>:</p><ul><li>Look for <strong>type</strong> values like ALL or index, which can be inefficient.</li><li>Check if <strong>possible_keys</strong> and <strong>keys</strong> are being used effectively. If <strong>possible_keys</strong> is NULL, it means no indexes are found useful for the query.</li><li>The <strong>rows</strong> column gives an indication of how many rows the database needs to look through to execute the query. Fewer rows generally mean better performance.</li><li>In the <strong>Extra</strong> column, look for things like “Using index” (good) or “Using temporary” and “Using filesort” (can be bad for performance).</li></ul><p><strong>Optimization Tips</strong>:</p><ul><li>If a query scans many rows, consider adding an index.</li><li>Rewrite the query to make it more efficient, for instance by using joins instead of sub-queries.</li><li>Consider the physical design of your database. For example, partitioning large tables can improve performance.</li></ul><h3><strong>Nested Queries vs Joins</strong></h3><p>In database management, “nested queries” and “joins” are two different methods for retrieving data from multiple tables. Understanding the differences between them is crucial for efficient database querying and management.</p><h4>Nested Queries (Subqueries)</h4><p><strong>Definition:</strong></p><ul><li>A subquery is a query nested inside another query.</li><li>It’s enclosed within parentheses and typically executed first, providing a result that is used by the outer query.</li></ul><p><strong>Usage:</strong></p><ul><li>Used to retrieve data that will be used in the main query’s condition or filter.</li><li>Commonly employed when dealing with aggregate functions, IN, EXISTS, or comparisons.</li></ul><p><strong>Performance:</strong></p><ul><li>It may have performance implications as they are executed for each row in the outer query.</li><li>Care should be taken to optimize subqueries to avoid unnecessary overhead.</li></ul><p><strong>Readability:</strong></p><ul><li>It can make the SQL code more readable and concise, especially for complex queries.</li><li>Useful when the logic involves multiple conditions or calculations.</li></ul><h4>Joins</h4><p><strong>Definition:</strong></p><ul><li>Joins are used to combine rows from two or more tables based on related columns.</li><li>There are different types of joins such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN.</li></ul><p><strong>Usage:</strong></p><ul><li>Utilised to retrieve data from multiple tables by linking them based on a common column.</li><li>It offers more flexibility when it comes to combining and filtering data.</li></ul><p><strong>Performance:</strong></p><ul><li>Generally more efficient than subqueries, especially for large datasets.</li><li>Joins can be optimized using indexes on the join columns.</li></ul><p><strong>Readability:</strong></p><ul><li>This may result in longer and more complex SQL statements, but they can be easier to understand when dealing with simple relationships.</li></ul><h4><strong>Considerations</strong></h4><p><strong>Data Complexity:</strong></p><ul><li>Use subqueries when dealing with one-to-one or one-to-few relationships.</li><li>Use joins when working with one-to-many or many-to-many relationships.</li></ul><p><strong>Performance vs Readability:</strong></p><ul><li>Balance the need for performance with the desire for readable and maintainable code.</li><li>Optimize queries based on the specific use case and database structure.</li></ul><p><strong>Indexing:</strong></p><ul><li>Ensure relevant columns in joined tables are indexed for better query performance.</li></ul><h3>Understanding Indexes in Databases: A Comprehensive Overview</h3><h3>Introduction:</h3><p>Indexes play a crucial role in enhancing the performance of databases by facilitating efficient data retrieval and manipulation. As a database developer and administrator, it’s imperative to grasp the significance of indexes and make informed decisions regarding their implementation. In this talk, we will delve into the key aspects of indexes, their types, and the impact they have on read-and-write operations.</p><h3>Use of Indexes:</h3><p>An index is a data structure that provides a quick and efficient way to look up records in a database based on the values in one or more columns. The primary purpose of indexes is to speed up the retrieval of data, reducing the time it takes to execute queries. By creating indexes on columns frequently used in WHERE clauses, JOIN conditions, or ORDER BY clauses, you can significantly enhance the database’s query performance</p><h3>Single vs. Composite Indexes:</h3><ul><li><strong>Single Indexes:</strong> These indexes are created on a single column. They are effective when queries predominantly involve filtering or sorting based on a specific column. Single indexes are straightforward but may not be sufficient for complex query scenarios.</li><li><strong>Composite Indexes:</strong> These indexes involve multiple columns. They are useful when queries involve conditions or sorting on multiple columns. While composite indexes can be more powerful, it’s essential to carefully consider the order of columns in the index, as it impacts the index’s effectiveness for different query patterns.</li></ul><h3>Reads and Writes Impact:</h3><ul><li><strong>Reads:</strong> Indexes significantly improve read performance by allowing the database engine to locate and retrieve the required data more quickly. Queries that leverage indexes can exhibit a substantial reduction in execution time, leading to a more responsive application.</li><li><strong>Writes:</strong> While indexes enhance read performance, they can impact write operations. Each insert, update, or delete operation may require updating the corresponding indexes, leading to additional overhead. Striking the right balance between read and write performance is crucial when designing and maintaining indexes.</li></ul><h3>Importance of Balanced Indexes:</h3><p>A balanced index is one that optimally supports both read and write operations. Unbalanced indexes, where read or write performance is disproportionately favoured, can lead to suboptimal database performance. Striking a balance involves choosing the right type of indexes, optimizing their usage, and periodically reviewing and adjusting them based on the evolving workload.</p><p>In conclusion, as a database developer and administrator, understanding the intricacies of indexes is vital for creating a well-optimized and responsive database system. By strategically implementing and maintaining indexes, you can ensure that your database efficiently handles both read and write operations, providing a seamless experience for users and applications alike.</p><h3>Database Optimizations for Improved Performance</h3><h4>Introduction:</h4><p>Optimizing database performance is a crucial aspect of ensuring efficient and responsive applications. As a database developer and administrator, it is essential to implement various strategies and best practices to enhance the overall speed and reliability of database operations. In this discussion, we’ll explore key optimizations that contribute to a well-tuned database system.</p><h4>Aliases for Better Readability:</h4><p>Using aliases in your SQL queries can significantly improve the readability of your code. Instead of using lengthy table and column names, assigning aliases provides a concise and clear representation of your queries. This not only makes the code more readable for developers but also aids in maintenance and troubleshooting.</p><p>Example:</p><pre>-- Without Aliases<br>SELECT customers.customer_id, customers.customer_name, orders.order_date<br>FROM customers<br>JOIN orders ON customers.customer_id = orders.customer_id;<br><br>-- With Aliases<br>SELECT c.customer_id, c.customer_name, o.order_date<br>FROM customers AS c<br>JOIN orders AS o ON c.customer_id = o.customer_id;</pre><h4>Select Only What is Needed:</h4><p>Minimizing the amount of data retrieved from the database can significantly boost performance. Rather than fetching all columns from a table, explicitly specify only the columns required for the task at hand. This reduces network overhead, speeds up query execution, and conserves system resources.</p><p>Example:</p><pre>-- Selecting All Columns<br>SELECT * FROM products WHERE category = &#39;Electronics&#39;;<br><br>-- Selecting Only Needed Columns<br>SELECT product_id, product_name FROM products WHERE category = &#39;Electronics&#39;;</pre><h4>Query Sanitization:</h4><p>Ensuring the security of your database is paramount. Implementing query sanitization techniques helps prevent SQL injection attacks, where malicious code is injected into queries. Use parameterized queries or prepared statements to sanitize user inputs and eliminate the risk of unauthorized access or data manipulation.</p><p>Example (Parameterized Query):</p><pre>-- Vulnerable to SQL Injection<br>SELECT * FROM users WHERE username = &#39;admin&#39; AND password = &#39;password&#39;;<br><br>-- Using Parameterized Query<br>SELECT * FROM users WHERE username = @username AND password = @password;</pre><h4>Parameters (Min, Max, MaxIdleTimeout) and Performance Improvement:</h4><p>Fine-tuning parameters such as the minimum and maximum pool size, as well as the maximum idle timeout, can significantly impact database performance. These parameters control how connections are managed, ensuring a balance between resource utilization and responsiveness.</p><ul><li>Min Pool Size: Sets the minimum number of connections in the pool, reducing connection establishment overhead.</li><li>Max Pool Size: Limits the maximum number of connections in the pool, preventing resource exhaustion.</li><li>Max Idle Timeout: Specifies the maximum time a connection can remain idle before being closed, freeing up resources.</li><li>Max Database Connection Limit: Understanding and setting an appropriate maximum database connection limit is crucial for managing system resources. Setting an excessively high limit can lead to resource contention, while a low limit may result in poor application performance. It is essential to strike a balance based on the system’s capacity and workload.</li></ul><h4>Conclusion:</h4><p>Optimizing a database involves a combination of thoughtful design, efficient query writing, and proper configuration of database parameters. By implementing strategies such as aliasing, selective column retrieval, query sanitization, and tuning connection parameters, database developers and administrators can create a responsive and secure environment for their applications. Regular monitoring and adjustments based on the evolving needs of the system are key to maintaining optimal database performance.</p><h3>Scaling, Maintenance, and Security in Database Management: A Comprehensive Overview</h3><p>Scaling a database involves ensuring that it can handle increased workload or growing data efficiently. There are various strategies for scaling databases, and the choice depends on the specific requirements, architecture, and constraints of the system. Here are some common approaches:</p><p><strong>Vertical Scaling (Scaling Up):</strong></p><ul><li><strong>Explanation:</strong> Increase the resources (CPU, RAM, storage) of a single server to handle more load.</li><li><strong>Example:</strong> Upgrading the hardware of a server by adding more RAM or faster processors.</li></ul><p><strong>Horizontal Scaling (Scaling Out):</strong></p><ul><li><strong>Explanation:</strong> Distribute the load across multiple servers by adding more machines to the database cluster.</li><li><strong>Example:</strong> Sharding the database, where each shard is a separate database instance that stores a subset of the data.</li></ul><p><strong>Database Replication:</strong></p><ul><li><strong>Explanation:</strong> Create and maintain copies of the database on multiple servers to distribute read queries and provide fault tolerance.</li><li><strong>Example:</strong> Setting up master-slave replication, where writes go to the master and reads can be distributed among multiple read-only replicas.</li></ul><p><strong>Partitioning:</strong></p><ul><li><strong>Explanation:</strong> Divide a large database into smaller, more manageable partitions.</li><li><strong>Example:</strong> Range partitioning based on certain criteria (e.g., date ranges), ensuring that each partition can be managed independently.</li></ul><p><strong>Caching:</strong></p><ul><li><strong>Explanation:</strong> Use in-memory caches to store frequently accessed data, reducing the load on the database.</li><li><strong>Example:</strong> Implementing a caching layer using tools like Redis or Memcached to store query results or frequently accessed records.</li></ul><p><strong>Load Balancing:</strong></p><ul><li><strong>Explanation:</strong> Distribute incoming requests across multiple database servers to ensure even load distribution.</li><li><strong>Example:</strong> Using a load balancer to distribute read and write requests among multiple database nodes.</li></ul><p><strong>Database Sharding:</strong></p><ul><li><strong>Explanation:</strong> Divide a large database into smaller, independent shards that can be distributed across different servers.</li><li><strong>Example:</strong> Sharding a user database based on the first letter of the username, so users with names starting with A-M are on one shard, and N-Z on another.</li></ul><p><strong>NoSQL Databases:</strong></p><ul><li><strong>Explanation:</strong> Use a NoSQL database that is designed for horizontal scalability and can handle large amounts of unstructured data.</li><li><strong>Example:</strong> Adopting MongoDB or Cassandra for a system with high write and read throughput requirements</li></ul><p><strong>Database Denormalization:</strong></p><ul><li><strong>Explanation:</strong> Store redundant data to eliminate the need for expensive joins, improving query performance.</li><li><strong>Example:</strong> Storing calculated values in a separate column to avoid recalculating them in each query.</li></ul><p>When scaling a database, it’s often beneficial to combine multiple strategies based on the specific needs and constraints of the application. Additionally, ongoing monitoring and optimization are crucial to ensuring the scalability solutions continue to meet the system’s requirements as it evolves.</p><h3>Maintaining Databases</h3><h4>Automated Backups and Failover Planning:</h4><ul><li>Implement automated backup routines to regularly capture database snapshots. Additionally, establish failover mechanisms to seamlessly switch to backup servers or instances in case of hardware failures or other disruptions.</li></ul><h4>Optimization for Resilience:</h4><ul><li>Regularly optimize the database for resilience by fine-tuning performance parameters, ensuring failover configurations are effective, and maintaining efficient data structures. This enhances the database’s ability to handle unexpected incidents.</li></ul><h4>Security Measures and Redundancy:</h4><ul><li>Strengthen security measures with access controls, encryption, and authentication. Integrate redundant systems to enhance resilience against security threats and ensure continuity in the event of a security breach.</li></ul><h4>Monitoring, Alerts, and Automated Recovery:</h4><ul><li>Set up continuous monitoring with real-time alerts for potential issues. Implement automated recovery procedures to respond swiftly to detected problems, such as initiating failovers or restoring from backups.</li></ul><h4>Timely Software Updates and Compatibility Checks:</h4><ul><li>Stay current with software updates for the database management system and related tools. Ensure compatibility with failover mechanisms and backup systems to maintain a robust and up-to-date database environment.</li></ul><h4>Comprehensive Documentation and Training for Recovery:</h4><ul><li>Maintain comprehensive documentation detailing failover procedures, backup restoration steps, and recovery protocols. Provide training for the operations team on executing these processes effectively to minimize downtime during critical situations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffb0f68ede00" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/getting-your-database-production-ready-ffb0f68ede00">Getting Your Database production ready</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton Pattern in Golang]]></title>
            <link>https://towardsdev.com/singleton-pattern-in-golang-c83006c768f3?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/c83006c768f3</guid>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 10:42:03 GMT</pubDate>
            <atom:updated>2023-06-03T15:23:09.001Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A Singleton pattern will provide us with a single instance of an object, and guarantee that there are no duplicates.<br>At the first call to use the instance, it is created and reused between all the parts in the application that need the use of particular behavior.</blockquote><h4>Common usage of singleton patterns around us:</h4><p>1. Database connection<br>2. SSH connection to a server<br>3. If you need to limit the access to some variable or space, you use a Singleton as the door to this variable.<br>And many more…</p><h4>General Guidelines we follow whenever using the Singelton pattern:</h4><p>1. We need a single, shared value, of some particular type<br>2. We need to restrict object creation of some type to a single unit along the entire program.</p><p><em>To showcase the singleton pattern, let’s try an example</em></p><p>Unique Counter<br>We will write a counter that holds the number of times it has been called during program execution. It shouldn’t matter how many instances we have of the counter, all of them must count the same value and it must be consistent between the instances.</p><h3>Requirements and acceptance criteria :</h3><p>There are some requirements and acceptance criteria to write the described single counter. They are as follows: <br>1. When no counter has been created before, a new one is created with the value 0 <br>2. If a counter has already been created, return this instance that holds the actual count <br>3. If we call the method AddOne, the count must be incremented by 1</p><h3>Implementation:</h3><p>We will implement a Singleton pattern. We’ll usually write a <em>static</em> method and instance to retrieve the Singleton instance in other languages like Java or C++.</p><p>In Go we don’t have the static, but we can achieve the same result by using the scope of the package.</p><p>First, we will create a struct containing the object we want. guarantee to be Singleton during the execution of the program:</p><pre>package singleton<br><br>import (<br> &quot;log&quot;<br> &quot;sync&quot;<br>)<br><br>type Singleton interface {<br> AddOne() int<br>}<br><br>type singelton struct {<br> count int<br>}<br><br>var instance *singelton<br><br>// GetInstance Basic instantiation of singleton object<br>func GetInstance() Singleton {<br> if instance == nil {<br>  log.Println(&quot;A new instance was created.&quot;)<br>  instance = new(singelton)<br> } else {<br>  log.Println(&quot;Single instance was already created&quot;)<br> }<br><br> return instance<br>}<br><br>func (s *singelton) AddOne() int {<br> s.count++<br> return s.count<br>}</pre><p>We created a GetInstance method that checks if the instance has not been initialized already (instance == nil), and creates an instance in the space already allocated in the line instance = new(singleton). Remember, when we use the keyword new, we are creating a pointer to an instance of the type between the parentheses.</p><p>The AddOne method will take the count of the variable instance, raise it by 1, and return the current value of the counter.</p><p>Let’s execute the program and check if the <strong><em>Singleton</em></strong> contract is followed</p><pre>package main<br><br>import &quot;github.com/Vishalj32/go-design-patterns/creational/singleton&quot;<br><br>func main() {<br> for i := 0; i &lt; 5; i++ {<br>  singleton.GetInstance()<br> }<br>}</pre><pre>vishaljain@Mac go-design-patterns % go run main.go <br>A new instance was created.<br>Single instance was already created<br>Single instance was already created<br>Single instance was already created<br>Single instance was already created</pre><p>In the above implementation, we have our first approach implementing <strong><em>Singleton</em></strong> in <strong><em>Golang</em></strong> and with goroutines to simultaneously run our <strong><em>Singleton</em></strong>.</p><p>The problem visible in this code is that <strong><em>several goroutine</em></strong> routines could evaluate the first check and all would create a singleton instance and replace one another. There is no guarantee of which instance will be returned in the code above and other additional operations on the instance may be inconsistent with developer expectations and stealth problems may occur at run time.</p><h4>Implementation with Locks &amp; Mutex</h4><p>In this implementation, we will create a thread-safe Singleton instance access. We will be utilising sync.Mutex package to create a lock while creating a new instance.</p><pre>package singleton<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;sync&quot;<br>)<br><br>type Singleton interface {<br> AddOne() int<br>}<br><br>type singelton struct {<br> count int<br>}<br><br>var instance *singelton<br>var lock = &amp;sync.Mutex{}<br><br>// GetInstanceMutex thread-safe singleton instantiation with single lock<br>func GetInstanceMutex() Singleton {<br> lock.Lock()<br> defer lock.Unlock()<br><br> if instance == nil {<br>  log.Println(&quot;A new instance was created.&quot;)<br>  instance = new(singelton)<br> } else {<br>  log.Println(&quot;Single instance was already created&quot;)<br> }<br> return instance<br>}<br><br>func (s *singelton) AddOne() int {<br> s.count++<br> return s.count<br>}</pre><p>This implementation also has a drawback, problem with this approach is excessive blocking even when it would not be necessary to do so in case the instance has already been created and should simply have returned the singleton instance. If our program is written to become highly concurrent, this can generate a bottleneck, since only one goroutine routine can get the <em>singleton</em> instance at a time, making it our slower solution.</p><p>Let’s try another approach.</p><h4>Check-Lock-Check Implementation</h4><p>One way to improve and ensure a minimum lock and still be safe for the goroutine is to use the pattern called “<strong>Check-Lock-Check</strong>” when acquiring locks.<br>The pattern works with the idea of checking first, <em>to minimize any aggressive blocking</em>, since an IF statement is less expensive than locking. Next time, we would have to wait and get the exclusive lock so that only one execution is inside that block at a single time. With the first scan and exclusive lock, there may be another goroutine that has the lock, so we would need to double-check inside the lock to avoid replacing the instance with another.</p><pre>package singleton<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br> &quot;sync/atomic&quot;<br>)<br><br>type Singleton interface {<br> AddOne() int<br>}<br><br>type singelton struct {<br> count int<br>}<br><br>var instance *singelton<br>var lock = &amp;sync.Mutex{}<br><br>// GetInstanceMutexDoubleCheck thread-safe singleton instantiation with double lock<br>func GetInstanceMutexDoubleCheck() Singleton {<br> if instance == nil {<br>  lock.Lock()<br>  defer lock.Unlock()<br><br>  if instance == nil {<br>   fmt.Println(&quot;A new instance was created.&quot;)<br>   instance = new(singelton)<br>  } else {<br>   fmt.Println(&quot;Single instance was already created&quot;)<br>  }<br> } else {<br>  fmt.Println(&quot;Single instance was already created&quot;)<br> }<br><br> return instance<br>}</pre><p>This approach is faster and much safer, but it is still not perfect. Because there is no atomic check on the instance storage.</p><p>Using the <strong><em>sync/atomic</em></strong> package, we can load and set atomically a flag that indicates whether or not we initialize our instance.</p><p>Check the code below:</p><pre>package singleton<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br> &quot;sync/atomic&quot;<br>)<br><br>type Singleton interface {<br> AddOne() int<br>}<br><br>type singelton struct {<br> count int<br>}<br><br>var instance *singelton<br>var lock = &amp;sync.Mutex{}<br>var atomicInt uint64<br><br>// GetInstanceAtomic creates an instance using atomic variable and lock<br>func GetInstanceAtomic() Singleton {<br> if atomic.LoadUint64(&amp;atomicInt) == 1 {<br>  fmt.Println(&quot;Single instance was already created&quot;)<br>  return instance<br> }<br> lock.Lock()<br> defer lock.Unlock()<br><br> if atomicInt == 0 {<br>  instance = new(singelton)<br>  atomic.StoreUint64(&amp;atomicInt, 1)<br> }<br> fmt.Println(&quot;A new instance was created.&quot;)<br> return instance<br>}</pre><p>All these approaches have their own benefits and drawbacks. They are also a little complicated to implement and work around ease-fully.</p><p>Let’s look into a Golang-specific approach that is clean and more powerful.</p><h4>sync.Once Implementation</h4><p>We have the type “<strong><em>Once</em></strong>” in the <strong><em>sync</em></strong> library, remembering that this native library in Golang is very powerful and we have to exploit it as much as we can, the sync. Once an object will perform an action exactly once and not more, it was what was missing for our code to get even more powerful and clean.</p><pre>package singleton<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br> &quot;sync/atomic&quot;<br>)<br><br>type Singleton interface {<br> AddOne() int<br>}<br><br>type singelton struct {<br> count int<br>}<br><br>var instance *singelton<br>var once sync.Once<br><br>// GetInstanceSyncOnce singleton instantiation using sync.Once package<br>func GetInstanceSyncOnce() Singleton {<br> if instance == nil {<br>  once.Do(<br>   func() {<br>    fmt.Println(&quot;A new instance was created.&quot;)<br>    instance = new(singelton)<br>   })<br> } else {<br>  fmt.Println(&quot;Single instance was already created&quot;)<br> }<br> return instance<br>}</pre><pre>vishaljain@Mac go-design-patterns % go run main.go <br>A new instance was created.</pre><h4>Conclusion</h4><p>We have seen multiple implementations of the singleton pattern. Just keep in mind that the Singleton pattern will give you the power to have a unique instance of some struct in your application and that no package can create any clone of this struct.</p><p>The ideal is undoubtedly the use of <strong><em>sync.Once</em></strong> that guarantees us the uniqueness and that is “<strong>Thread Safe</strong>” guaranteeing that a “<a href="https://blog.golang.org/race-detector"><strong><em>Race Condition</em></strong></a><strong><em>” </em></strong>does not occur, it only allows the function to be executed only once Golang flexibility and automated all the complexity we would have in other languages if we were to work with competition and simultaneity</p><p>With Singleton, you are also hiding the complexity of creating the object, in case it requires some computation, and the pitfall of creating it every time you need an instance of it if all of them are similar. All this code writing, checking if the variable already exists, and storage, are encapsulated in the singleton and you won’t need to repeat it everywhere if you use a global variable.</p><h4>Source Code</h4><p><a href="https://github.com/Vishalj32/go-design-patterns">https://github.com/Vishalj32/go-design-patterns</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c83006c768f3" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/singleton-pattern-in-golang-c83006c768f3">Singleton Pattern in Golang</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing LRUCache in Golang]]></title>
            <link>https://towardsdev.com/implementing-lrucache-in-golang-fb2037831fc6?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb2037831fc6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Sat, 08 May 2021 06:18:00 GMT</pubDate>
            <atom:updated>2021-05-14T11:33:01.290Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Cache</strong>: The more the data grows, the more the data database transactions grow, and the importance of cache grows.</blockquote><h3>Introduction</h3><p>While scaling our microservices, we might have a question about whether we should implement caching mechanisms or optimize our database layers. Both have their own pros and cons depending upon our requirements and architecture. In this article, we would mainly be discussing caching and implementing simplistic <em>LRUCache.</em></p><p>Implementing a caching mechanism or cache store helps us reducing the load on our database engines (indirectly saving us some money as well!!)</p><h4>Why caching?</h4><p>Even though horizontally scaling the application would add more resources and allow the database to serve our API requests. However, we would reach a certain point where the database can’t handle the request traffic.</p><p>On an API level, we can add multiple optimizations like pagination, database pooling, CQRS (Command-Query Request Segregation), caching as per our requirements.</p><p>There are many implementations of caches readily available,</p><ul><li>Redis</li><li>Memcached</li><li>Hazelcast</li></ul><p>We would be discussing an in-memory cache abstraction i.e. LRUCache (Least Recently Used Cache)</p><h4>Implementation</h4><p>Let’s start by defining the structure of our cache.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cd7b3ddb9a3c21d3882685d1cb0bec2/href">https://medium.com/media/2cd7b3ddb9a3c21d3882685d1cb0bec2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3201806929288c0c685aaa5fafa18b9d/href">https://medium.com/media/3201806929288c0c685aaa5fafa18b9d/href</a></iframe><p>LRUCache:</p><ul><li>Capacity: Number of elements that can be stored in the cache.</li><li>List: DoublyLinkedList for storing the cache values using <a href="https://golang.org/pkg/container/list/">container/list</a> provided by go packages.</li><li>Elements: Map to store the keys and pointer to the values stored in the list.</li></ul><p>We would be defining the below methods for our cache.</p><ol><li>Get</li><li>Put</li><li>Keys</li><li>Remove</li><li>Purge</li></ol><h4>Get</h4><p>As the cache stores the values in a map with keys and values stored in a list.</p><p>We check whether our key is present in the map, return the value stored in the list for the key or return -1.</p><p>While returning the value, we also move it to the front of the list to maintain the logic of <em>least recently used</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/689a15cba3166f3809f35c76ee3b7650/href">https://medium.com/media/689a15cba3166f3809f35c76ee3b7650/href</a></iframe><h4>Put</h4><p>Storing the values in cache follows the below steps:</p><ul><li>If the key is found in the cache, move it to the front of the list and store the new value.</li><li>Else, check the current capacity of the cache, in case of overflowing we remove the back entry from the list.</li><li>Store the new element at the front of the list.</li></ul><p>As the above steps suggest while checking the capacity we remove the back element from the cache, which defines our use case of <em>least recently used</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bacfe75e9e705ac89f257fdf068f3770/href">https://medium.com/media/bacfe75e9e705ac89f257fdf068f3770/href</a></iframe><h4>RecentlyUsed</h4><p>Returns the value from the front of the list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75250d5224b7a43e0acbbefc018f9481/href">https://medium.com/media/75250d5224b7a43e0acbbefc018f9481/href</a></iframe><h4>Remove</h4><p>Here we check whether the cache consists of the key intended to be removed, if found we remove the key from the list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbbc4a19e71fabd4b86dfb57d98ac3ef/href">https://medium.com/media/dbbc4a19e71fabd4b86dfb57d98ac3ef/href</a></iframe><p>With this, we have completed our definition for all our methods required for our LRUCache implementation.</p><p>Code related to the implementation is available <a href="https://github.com/Vishalj32/lru-cache">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb2037831fc6" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/implementing-lrucache-in-golang-fb2037831fc6">Implementing LRUCache in Golang</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Stack in Golang]]></title>
            <link>https://towardsdev.com/implementing-stack-in-golang-30e4c4c9f941?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/30e4c4c9f941</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Sat, 27 Mar 2021 09:46:01 GMT</pubDate>
            <atom:updated>2021-03-30T11:42:04.964Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we would be discussing implementing a stack in Golang.<br>It would be a continuation of my series of implementing Data Structures in Golang</p><ul><li><a href="https://vishalj64.medium.com/queue-implementation-in-golang-a4c3319c120f">Queue</a></li><li><a href="https://vishalj64.medium.com/linkedlist-implementation-in-golang-50515483ccbe">LinkedList</a></li></ul><h4>Introduction</h4><p>What is Stack?</p><p>Stack is a simple data structure used for storing data. In a stack, the order in which the data arrives is of the most importance.</p><p>Stack is an ordered list in which insertion and deletion are done at the end, known as the <em>top</em>. The last element inserted in the stack is the first element to be deleted/removed first.<br>It is known as Last In First Out (LIFO).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*c213gNw3U870mzSGt6X-Sw.png" /><figcaption>Stack</figcaption></figure><h4>Implementation</h4><p>We would be implementing a stack backed by a simple array and defining the following operations for a stack.</p><p><strong>Main Operations:</strong></p><ul><li>Push()</li><li>Pop()</li></ul><p><strong>Auxillary Operations:</strong></p><ul><li>Peek()</li><li>Size()</li><li>IsEmpty()</li><li>IsFull()</li></ul><p>So, let us start first with defining our backbone structure for the Stack object.<br>It will have the following structure:</p><ul><li>Array: to store the data</li><li>Top: pointer to the top of the stack</li><li>Capacity: current capacity of the stack.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fa05720abb52e4309a4bfb7af11198d/href">https://medium.com/media/6fa05720abb52e4309a4bfb7af11198d/href</a></iframe><p>Push():</p><p>This operation will take the data as the input, and store the same, at the same time the top variable is incremented to point to the last element.</p><p>If we try to insert an element when the stack has reached its capacity, it is known as <em>“overflow”.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a938079d2a86661d43481ab0a4124c5/href">https://medium.com/media/3a938079d2a86661d43481ab0a4124c5/href</a></iframe><p>Pop():</p><p>This method will return the data present at the top of the stack and decrement the top pointer to point to the latest element in the stack.</p><p>If we try to pop out of an empty stack, it is known as <em>“underflow”</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8652dd06a769bc538caf9f5f8b3ccb76/href">https://medium.com/media/8652dd06a769bc538caf9f5f8b3ccb76/href</a></iframe><p>Peek():</p><p>The Peek method is the same as that of Pop, the only difference is that it does not delete the top element from the stack.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d06c206c17738190a5913af2a724936/href">https://medium.com/media/2d06c206c17738190a5913af2a724936/href</a></iframe><p>The overall code for the Stack would look like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f2b44e7cae96636bef8cddc77547ede/href">https://medium.com/media/6f2b44e7cae96636bef8cddc77547ede/href</a></iframe><p>This completes our implementation of an array backed stack, now let us test the same using the below snippet</p><pre>func StackRunner() {<br>stack := NewStack(10)<br>stack.Push(1)<br>stack.Push(2)<br>stack.Push(3)</pre><pre>stack.Print()</pre><pre>stack.Pop()<br>stack.Print()<br>fmt.Println(&quot;Size := &quot;, stack.Size())<br>}</pre><p>The output would be like below:</p><pre>[1,2,3]<br>[1,2]<br>Size :=  2</pre><h4>Conclusion</h4><p>That brings us to the end of the article, thank you for your time, and in case you want to refer to the whole code, it is available <a href="https://github.com/Vishalj32/Datastructures_in_GO/tree/master/Stack">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30e4c4c9f941" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/implementing-stack-in-golang-30e4c4c9f941">Implementing Stack in Golang</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Queue Implementation in Golang]]></title>
            <link>https://vishalj64.medium.com/queue-implementation-in-golang-a4c3319c120f?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4c3319c120f</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Sun, 14 Mar 2021 09:23:52 GMT</pubDate>
            <atom:updated>2021-03-14T09:23:52.485Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we would be discussing the implementation of Queue(backed by Array/Slice) in Golang<br>This would be a follow-up to my recent article:</p><ul><li><a href="https://vishalj64.medium.com/linkedlist-implementation-in-golang-50515483ccbe">LinkedList Implementation in Golang</a></li></ul><h4><strong>Introduction</strong></h4><p>A queue is an abstract data structure (ADT) that follows a particular order in which the operations are performed.<br>It follows the First In First Out (LIFO) order for operations.<br>In a layman example, a queue is any queue of consumers for a resource where the consumer that came first is served first.</p><p>The difference between a queue and a stack is the removal order, in a stack, we remove the item the most recently added; in a queue, we remove the item the least recently added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*UIY5nY4m3QI0SDO8a9ZImA.png" /></figure><h4>Representation</h4><p>We would start by defining the basic building block for our implementation i.e. defining a struct for Queue that would be backed by Array or a slice in golang terminology.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cb988501a4ce6370e50f5089f687331/href">https://medium.com/media/7cb988501a4ce6370e50f5089f687331/href</a></iframe><p><strong>Variables</strong></p><ul><li>Queue: backed by an integer slice which will hold our data.</li><li>Front: Pointing towards the head position of the queue.</li><li>Back: Pointing towards the end position of the queue.</li></ul><h4>Operations</h4><p>We would be defining the below operations on our queue for demonstration purposes.</p><ul><li>Add()</li><li>Remove()</li><li>Peek()</li><li>Size()</li><li>Print()</li></ul><p>So, let us start with implementing the above-defined methods.</p><p>Before we start with the implementation we would be creating a method that would create a new ArrayQueue object which will be utilized by our defined methods.</p><h4>NewQueue:</h4><p>This method will create a new instance of our Queue with the initial capacity as a parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56e120d4e240bbbf0ab4859bb471028b/href">https://medium.com/media/56e120d4e240bbbf0ab4859bb471028b/href</a></iframe><h4>Add:</h4><p><em>Add</em> method will take in data as a parameter which in our instance would be of type int.<br>As we know Queue follows <strong><em>FIFO</em></strong> order for insertion and removal of data, thus the data would be added at the front of the queue and will be moved further upon additions of a new element.<br>We will also be resizing the queue whenever we reach the capacity and the resizing logic will be present in the <em>Add</em> method itself.</p><blockquote><strong><em>Add method can also be referred to as Enqueue.</em></strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2508ef15fe5690c3a293f9f07a8b2e33/href">https://medium.com/media/2508ef15fe5690c3a293f9f07a8b2e33/href</a></iframe><h4>Remove:</h4><p>Remove or Dequeue method will return the data from the back of the queue and delete the same from the queue.</p><p>While dequeuing, we would be incrementing the front to point to the next element in the queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fadab445256f1e4cc69c02284944125/href">https://medium.com/media/7fadab445256f1e4cc69c02284944125/href</a></iframe><h4>Peek:</h4><p>Peek is similar to the remove/dequeue method, the only difference between them is that while using <em>Peek </em>we will not the deleting the element from the queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6860c1228384845c8846f35420205de3/href">https://medium.com/media/6860c1228384845c8846f35420205de3/href</a></iframe><h4>Size:</h4><p>The size of the queue will be calculated by an arithmetic subtraction between the <em>Back</em> location and the <em>Front</em> location of the queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d5e08345c123e6841bd70c608bb769a/href">https://medium.com/media/5d5e08345c123e6841bd70c608bb769a/href</a></iframe><h4>Print:</h4><p>To print all the elements in the queue we would iterate over the queue from location <strong>Front -&gt; Back</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ab488fb771ccbbd47fff2fc2981ccf2/href">https://medium.com/media/6ab488fb771ccbbd47fff2fc2981ccf2/href</a></iframe><p>Now that we have completed our implementation it’s time to test the <em>ArrayQueue</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/012c48bcfe38048ff5c160a7bb73ce36/href">https://medium.com/media/012c48bcfe38048ff5c160a7bb73ce36/href</a></iframe><p><strong>Output:</strong></p><pre>1 | 2 | 3 | <br>Size :=  3<br>2 | 3 | <br>Size :=  2<br>Peek :=  2<br>Size :=  2</pre><h4>Conclusion</h4><p>This brings us to the end of the article. Thank you for your time.<br>The code in the discussion is available at <a href="https://github.com/Vishalj32/Datastructures_in_GO/tree/master/Queue">this</a> link.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4c3319c120f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LinkedList Implementation in Golang]]></title>
            <link>https://vishalj64.medium.com/linkedlist-implementation-in-golang-50515483ccbe?source=rss-24887eee8868------2</link>
            <guid isPermaLink="false">https://medium.com/p/50515483ccbe</guid>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[singly-linked-list]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Vishal Jain]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 11:09:44 GMT</pubDate>
            <atom:updated>2021-03-07T11:09:44.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>If a reader with a basic understanding of Golang might know that it has data structures like array, slice, map.<br>But being accustomed to Java, I missed the support of the Collections framework, its simplicity in usage, and multiple options like HashMap, TreeMap, ConcurrentHashMap, etc. which we can use as per our requirements.</p><p>Thus it led me to the question of whether if we can implement the same Java Collections in Golang from a curiosity perspective. <br>I am starting with the first of such implementation with LinkedList.</p><p>Let’s start with our implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*57fD8LqGKjn3jNr8JpfR2w.png" /><figcaption>LinkedList</figcaption></figure><h3>LinkedList</h3><p>A linked list is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers.</p><h4>Why LinkedList?</h4><p>As arrays are contiguous data structures, they can be used to store linear data which has their size already fixed, so the user will need to know the space required by data before implementation.<br>If a requirement where we have to maintain a dynamic structure, i.e. we don&#39;t know the size of data or avoid allocating larger array size if it might not be used later “LinkedList” can come in handy for our use case.</p><h4>Representation:</h4><p>A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL.<br>Each node in a list consists of at least two parts:</p><ul><li>Data</li><li>Pointer i.e. reference to the next node.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7373abc725d29792f59ce537d3d7b961/href">https://medium.com/media/7373abc725d29792f59ce537d3d7b961/href</a></iframe><p>We will be implementing a LinkedList for integer node value, and also provide the below methods</p><ul><li>Insert() / InsertAtPosition()</li><li>GetValue()</li><li>Print()</li><li>DeleteByValue() / DeleteByPosition()</li></ul><h4>1. Insert a node element in the LinkedList</h4><p>To insert an element in our LinkedList we would need to perform the below steps</p><ul><li>If the LinkedList is empty, then add the node element as the first element</li></ul><p>OR</p><ul><li>If LinkedList is not empty, traverse till the end of the list and insert the element as the last element.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/044f51d081ca8a0aea56e0faa57ff99b/href">https://medium.com/media/044f51d081ca8a0aea56e0faa57ff99b/href</a></iframe><h4>2. Insert a node value at a certain position in LinkedList</h4><p>Let’s say we need to insert a new element at a certain position in the LinkedList, so we need to perform the below steps</p><p>In such a case, we have to traverse the list till the provided <strong>n</strong>th node &amp; change its pointer to point to the new node.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd403235a3b2001b02484db3b9c51a8a/href">https://medium.com/media/fd403235a3b2001b02484db3b9c51a8a/href</a></iframe><h4>3. Printing LinkedList Nodes</h4><p>To print the node values we would be traversing the LinkedList single node at a time and printing the same till the pointer hits <em>“nil” </em>i.e. the end of the LinkedList.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be8ee0c9acad1c21b65a33b954fe4aae/href">https://medium.com/media/be8ee0c9acad1c21b65a33b954fe4aae/href</a></iframe><h4>4. Get LinkedList Node Value</h4><p>We would be implementing a search/get value based on the position.<br>To retrieve data, we would traverse till the position and return the value/print the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5e0ecaff1311d0ad7e5ed969b0de4b2/href">https://medium.com/media/b5e0ecaff1311d0ad7e5ed969b0de4b2/href</a></iframe><h4>5. Delete a node from LinkedList</h4><p>Removing a node from LinkedList is similar to that of Inserting nodes in LinkedList</p><p>Following are the steps we need to do to remove a node:</p><ol><li>Find the previous node of deleting a node</li><li>Change the next of previous node with the next of deleting a node</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/296709786b5ed77849fd305d5b61c316/href">https://medium.com/media/296709786b5ed77849fd305d5b61c316/href</a></iframe><p>Let’s say we don&#39;t know about the position of the node considered for deletion, we can do the same by deleting based on value.</p><ul><li>Traverse the list</li><li>Compare the given value to the current node value</li><li>if a match is found then, change the pointer value of the <em>pos-1 </em>node &amp; point it to the next node of deleting node</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0be4996abd6807cce89e8f9ef3e97021/href">https://medium.com/media/0be4996abd6807cce89e8f9ef3e97021/href</a></iframe><h3>Conclusion</h3><p>This article tried to explain the basic functionality of LinkedList.<br>Below are some advantages and disadvantages.</p><h4>Advantages:</h4><ol><li>Dynamic in size allocation.</li><li>Ease of insertion/deletion i.e O(n) in time complexity.</li></ol><h4>Disadvantages:</h4><ol><li>Random access is not allowed. We have to access elements sequentially starting from the first node.</li><li>Extra memory space for a pointer is required with each element of the list.</li><li>Not cache-friendly. Since array elements are contiguous locations, there is the locality of reference which is not there in the case of linked lists.</li></ol><blockquote>That’s all folks, hope this article has helped you in some understanding of LinkedList and its implementation in Golang.</blockquote><blockquote>Code is available on this <a href="https://github.com/Vishalj32/Datastructures_in_GO/tree/master/SinglyLinkedList">Github</a> link.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50515483ccbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>