<?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 Dmitrii Kumancev on Medium]]></title>
        <description><![CDATA[Stories by Dmitrii Kumancev on Medium]]></description>
        <link>https://medium.com/@dmkaban62?source=rss-d1d30ee7a16f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j6joGcudc9KEvnvP5eiVpw.jpeg</url>
            <title>Stories by Dmitrii Kumancev on Medium</title>
            <link>https://medium.com/@dmkaban62?source=rss-d1d30ee7a16f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 13:45:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dmkaban62/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[Social Media System Design: A Go Developer’s Blueprint]]></title>
            <link>https://medium.com/@dmkaban62/social-media-system-design-a-go-developers-blueprint-91195e277c07?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/91195e277c07</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[architectural-design]]></category>
            <category><![CDATA[social-media]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 09:23:33 GMT</pubDate>
            <atom:updated>2025-01-12T09:23:33.911Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the world of system design! In this article, we’ll dive into the process of building a simplified yet powerful social media platform using Go. By focusing on low-level system design principles, we’ll explore how to implement core features such as user registration, post creation, likes, comments, and a real-time notification system. This hands-on example will demonstrate how to architect a platform that’s not only modular and scalable but also efficient and maintainable.</p><p>Leveraging Go’s exceptional concurrency capabilities and proven design patterns like the Facade pattern, we’ll craft a streamlined architecture capable of handling multiple user interactions seamlessly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjjKRYfgCV6hjv52S3XO_w.png" /></figure><h3>Key Components of Our Design</h3><p>The social media platform we’re building focuses on these main features:</p><ul><li>User Management: Registering and managing user profiles.</li><li>Post Creation and Interactions: Creating posts, liking, and commenting.</li><li>Notifications: Alerting users to relevant actions like likes and comments.</li><li>Concurrency: Efficiently handling simultaneous user actions.</li></ul><h3>Core Components of the System</h3><p>Let’s break down the key components of our platform and see how each part integrates into the system.</p><ol><li><strong>User Management</strong></li></ol><p>The UserManager component is responsible for user registration and profile management. Each user has essential profile details like ID, name, and bio, and the manager ensures users can be added and retrieved efficiently. Some key functions are:</p><pre>type User struct {<br>    type User struct {<br>    ID             int<br>    Name           string<br>    Email          string<br>    Password       string<br>    DisplayPicture *string<br>    Bio            *string<br>    friends        map[int]*User<br>    posts          []*Post<br>}<br><br>type UserManager struct {<br>    users map[int]*User<br>    mu    sync.RWMutex<br>}<br><br>func (um *UserManager) AddUser(user *User) {<br>    um.mu.Lock()<br>    defer um.mu.Unlock()<br>    um.users[user.ID] = user<br>    fmt.Printf(&quot;User added: %d\n&quot;, user.ID)<br>}<br><br>func (um *UserManager) GetUserByID(userID int) (*User, error) {<br>    um.mu.RLock()<br>    defer um.mu.RUnlock()<br>    user, ok := um.users[userID]<br>    if !ok {<br>        return nil, fmt.Errorf(&quot;user not found&quot;)<br>    }<br>    return user, nil<br>}<br><br>func (um *UserManager) AddFriend(requesterID, receiverID int) error {<br>    requester, err := um.GetUserByID(requesterID)<br>    if err != nil {<br>        return err<br>    }<br><br>    receiver, err := um.GetUserByID(receiverID)<br>    if err != nil {<br>        return err<br>    }<br><br>    requester.AddFriend(receiver)<br>    receiver.AddFriend(requester)<br>    fmt.Printf(&quot;Friendship added between users: %d and %d\n&quot;, requesterID, receiverID)<br>    return nil<br>}</pre><p>In a real-world application, the UserManager would connect to a database, but here we use a map for simplicity.</p><ol><li><strong>Post Management</strong></li></ol><p>The PostManager handles user-generated content by managing posts, likes, and comments. This component allows users to create posts, like others’ posts, comment, and retrieve posts. Some key functions are:</p><pre>type Post struct {<br>    ID              int<br>    UserID          int<br>    Content         string<br>    IsPublished     bool<br>    URLs            []*string<br>    Likes           int<br>    Comments        []*Comment<br>    PublishedAt     time.Time<br>    CommentsEnabled bool<br>    HiddenFromUsers map[int]bool<br>}<br><br>type PostManager struct {<br>    posts map[int]*Post<br>    mu    sync.RWMutex<br>}<br><br>func (pm *PostManager) GetPost(postID int) (*Post, error) {<br>    pm.mu.RLock()<br>    defer pm.mu.RUnlock()<br><br>    post, exists := pm.posts[postID]<br>    if !exists {<br>        return nil, fmt.Errorf(&quot;post not found&quot;)<br>    }<br>    return post, nil<br>}<br><br>func (pm *PostManager) AddPost(post *Post, user *User) {<br>    pm.mu.Lock()<br>    defer pm.mu.Unlock()<br>    pm.posts[post.ID] = post<br><br>    user.AddPost(post)<br>}<br><br>func (pm *PostManager) LikePost(postID int) (*Post, error) {<br>    pm.mu.Lock()<br>    post := pm.posts[postID]<br>    pm.mu.Unlock()<br><br>    if post == nil {<br>        return nil, fmt.Errorf(&quot;post not found&quot;)<br>    }<br><br>    pm.mu.Lock()<br>    defer pm.mu.Unlock()<br><br>    post.Like()<br>    return post, nil<br>}</pre><p>The PostManager could interact with a database to store and retrieve posts, allowing for filtering by various criteria.</p><ol><li><strong>Notification Management</strong></li></ol><p>The NotificationManager is responsible for keeping users updated on platform activities, such as receiving a like or comment on their posts. Each notification type (like, comment, friend request) is sent through this manager, ensuring users are informed in real-time. Some key functions are:</p><pre>type Notification struct {<br>    ID      string<br>    Type    NotificationType<br>    Content string<br>    UserID  int<br>}<br><br>type NotificationManager struct {<br>    notifications map[int][]*Notification<br>    mu            sync.RWMutex<br>}<br><br>func (nm *NotificationManager) AddNotification(userID int, notificationType NotificationType, message string) {<br>    nm.mu.Lock()<br>    defer nm.mu.Unlock()<br><br>    notification := NewNotification(fmt.Sprintf(&quot;notification-%d&quot;, time.Now().UnixMicro()), notificationType, message, userID)<br>    nm.notifications[userID] = append(nm.notifications[userID], notification)<br>}<br><br>func (nm *NotificationManager) GetNotificationsForUser(userID int) ([]*Notification, error) {<br>    nm.mu.RLock()<br>    defer nm.mu.RUnlock()<br><br>    notifications, ok := nm.notifications[userID]<br>    if !ok {<br>        return nil, fmt.Errorf(&quot;user not found&quot;)<br>    }<br>    return notifications, nil<br>}</pre><p>With NotificationManager, we can notify users of interactions related to their posts, allowing for a more engaging experience. In a production system, notifications could be sent via channels or push notifications.</p><h3>Using the Facade Pattern with ActivityFacade</h3><p>To simplify interactions between different components, we use the <strong>Facade</strong> pattern. ActivityFacade combines the functionalities of UserManager, PostManager, and NotificationManager, providing a unified interface for our social media app.</p><pre>type ActivityFacade struct {<br>    userManager       *UserManager<br>    postManager       *PostManager<br>    notificationManager *NotificationManager<br>}<br><br>func (af *ActivityFacade) SendFriendRequest(requesterID, receiverID int) error {<br>    _, err := af.UserManager.GetUserByID(receiverID)<br>    if err != nil {<br>        return err<br>    }<br><br>    af.NotificationManager.AddNotification(receiverID, FriendRequestNotificationType, fmt.Sprintf(&quot;%d has sent you a friend request&quot;, requesterID))<br><br>    fmt.Printf(&quot;Friend request sent to user %d\n&quot;, receiverID)<br>    return nil<br>}<br><br>func (af *ActivityFacade) CommentPost(userID, postID int, content string) error {<br>    user, err := af.UserManager.GetUserByID(userID)<br>    if err != nil {<br>        return err<br>    }<br><br>    post, err := af.PostManager.CommentPost(user, postID, content)<br><br>    af.NotificationManager.AddNotification(post.UserID, CommentNotificationType, fmt.Sprintf(&quot;%d has commented on your post: %d&quot;, userID, post.ID))<br><br>    fmt.Printf(&quot;Comment added to post: %d\n&quot;, post.ID)<br>    return nil<br>}<br><br>func (af *ActivityFacade) HidePostFromUser(postID int, userID int) error {<br>    _, err := af.UserManager.GetUserByID(userID)<br>    if err != nil {<br>        return err<br>    }<br><br>    return af.PostManager.HidePostFromUser(postID, userID)<br>}</pre><p>With ActivityFacade, we can streamline user interactions with the platform, reducing the complexity of directly managing each subsystem. This approach makes the code more modular, maintainable, and easier to expand.</p><h3>Handling Concurrency</h3><p>In any social media platform, multiple users perform actions simultaneously. Go’s concurrency tools, particularly sync’s RWMutex, are ideal for handling concurrent reads and writes in a safe way.</p><p>Using RWMutex, we ensure that multiple users can read posts concurrently, but only one can like or comment at a time, preventing race conditions and data corruption.</p><h3>Conclusion and next steps</h3><p>Our low-level system design for a social media platform in Go provides a strong foundation for expanding features making it scalable and easy to maintain.</p><p>Potential areas for future enhancement include:</p><ul><li>Real-time Notifications using WebSockets or push notifications.</li><li>Advanced Privacy Controls for friend requests and posts.</li><li>Persistent Data Storage with a database to replace the in-memory maps.</li></ul><h3>Explore the Code</h3><p>For the complete implementation and to contribute to further enhancements, check out the <a href="https://github.com/DmitriiKumancev/low-level-design-systems">github repo</a>:<br><a href="https://github.com/DmitriiKumancev/low-level-design-systems/tree/main/social_media_platform">https://github.com/DmitriiKumancev/low-level-design-systems</a></p><p>This article is part of a <strong>5-part series</strong> on low-level design in Go. Stay tuned for more system design insights!</p><p><strong>Series:</strong></p><ol><li><a href="https://medium.com/@dmkaban62/diving-into-go-implementing-classic-elevator-scheduling-algorithms-fcfs-sstf-scan-and-look-4040c2de62f2">Elevator Scheduling Algorithms: FCFS, SSTF, SCAN, and LOOK</a></li><li><a href="https://medium.com/@dmkaban62/build-a-scalable-library-management-system-in-go-design-concurrency-tips-73029a2c73f6">Build a Scalable Library Management System in Go: Design &amp; Concurrency Tip</a></li><li>Building a Simple Social Media Platform in Go (<em>you’re here</em>)</li><li>Building a Vending Machine in Go <em>(soon)</em></li><li>Building a Parking Lot System in Go <em>(soon)</em></li></ol><blockquote><strong><em>That’s it! I hope my article was interesting and informative for you 😎😜</em></strong></blockquote><p><strong><em>Don’t forget about my github: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*qZ5yYjohuUj2fawd.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91195e277c07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Scalable Library Management System in Go: Design & Concurrency Tips]]></title>
            <link>https://medium.com/@dmkaban62/build-a-scalable-library-management-system-in-go-design-concurrency-tips-73029a2c73f6?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/73029a2c73f6</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 08:50:23 GMT</pubDate>
            <atom:updated>2024-12-26T08:50:23.331Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll dive into designing a <strong>Library Management System (LMS)</strong> using <strong>Go</strong>, focusing on its core features, design decisions, and key code snippets. Whether you’re a beginner or an experienced developer, this guide will help you understand how to build a scalable and efficient system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTiOoid6Ax1TfUP0nR1otg.png" /></figure><h3>Core Features of the Library Management System</h3><h4>1. Book Management</h4><p>The system supports multiple copies of each book, enabling efficient inventory tracking. Each book has properties like ID, title, author, publication year, and a slice of BookItem representing individual copies.</p><pre>type Book struct {<br>    ID            int<br>    BookItem      []BookItem<br>    Title         string<br>    Author        string<br>    PublishedYear string<br>    mu            sync.RWMutex<br>}</pre><h4>2. Member Management</h4><p>Members can borrow books, and the system tracks their borrowing history. Each member has a borrowing quota to limit the number of books they can borrow at once.</p><pre>type Member struct {<br>    ID              int<br>    Name            string<br>    ContactInfo     string<br>    CurrentBorrowed []*BookItem<br>    BorrowHistory   []*BookItem<br>}</pre><h4>3. Borrowing and Returning Books</h4><p>The system checks for available copies and updates their status when borrowed or returned. Borrowing history is also updated for each member.</p><pre>func (m *Member) AddBorrowedBook(bookItem *BookItem) {<br>    m.CurrentBorrowed = append(m.CurrentBorrowed, bookItem)<br>}<br><br>func (l *Library) BorrowBookByMember(memberID int, bookID int) *BookItem {<br>    // Logic to borrow a book<br>}</pre><h4>4. Concurrency Control</h4><p>Using Go’s concurrency features, the system handles multiple borrowing and returning requests simultaneously. The sync.RWMutex ensures thread-safe operations, preventing race conditions.</p><pre>func (b *Book) IsBookAvailable() bool {<br>    b.mu.RLock()<br>    defer b.mu.RUnlock()<br>    for _, bookCopy := range b.BookItem {<br>        if bookCopy.Status == Available {<br>            return true<br>        }<br>    }<br>    return false<br>}</pre><h4>5. Overdue Book Management</h4><p>The system checks for overdue books, notifies members, and may charge fines based on business rules.</p><pre>func (bi *BookItem) IsOverdue() bool {<br>    if bi.Status != Borrowed {<br>        return false<br>    }<br>    return time.Since(bi.LastBorrowed) &gt; time.Hour*24*7<br>}</pre><h3>Design Decisions</h3><h4>Why Go?</h4><p>Go was chosen for its simplicity, efficiency, and built-in concurrency support, which is essential for handling multiple requests in a library setting. Its strong typing and compile-time checks also reduce bugs and improve maintainability.</p><h4>Singleton Pattern for Library Instance</h4><p>The system uses a singleton pattern to manage a single instance of the library, centralizing operations like adding books and managing members.</p><pre>var (<br>   libraryInstance *Library<br>   once            sync.Once<br>)<br><br>func GetLibraryInstance() *Library {<br>   once.Do(func() {<br>       libraryInstance = &amp;Library{books: make(map[int]*Book), members: make(map[int]*Member)}<br>   })<br>   return libraryInstance<br>}</pre><h4>Encapsulation and Data Protection</h4><p>Mutexes (sync.RWMutex) protect shared resources, ensuring consistent states in a multi-user environment where multiple members interact with the system simultaneously.</p><h3>Explore the Code</h3><p>For the complete implementation and to contribute to further enhancements, check out the <a href="https://github.com/DmitriiKumancev/low-level-design-systems">github repo</a>:<br><a href="https://github.com/DmitriiKumancev/low-level-design-systems/tree/main/library-management_system">https://github.com/DmitriiKumancev/low-level-design-systems</a></p><p>This article is part of a <strong>5-part series</strong> on low-level design in Go. Stay tuned for more system design insights!</p><p><strong>Series:</strong></p><ol><li><a href="https://medium.com/@dmkaban62/diving-into-go-implementing-classic-elevator-scheduling-algorithms-fcfs-sstf-scan-and-look-4040c2de62f2">Elevator Scheduling Algorithms: FCFS, SSTF, SCAN, and LOOK</a></li><li>System Design: Library Management System</li><li>Building a Vending Machine in Go <em>(soon)</em></li><li>Building a Simple Social Media Platform in Go <em>(soon)</em></li><li>Building a Parking Lot System in Go <em>(soon)</em></li></ol><blockquote><strong><em>That’s it! I hope my article was interesting and informative for you 😎😜</em></strong></blockquote><p><strong><em>Don’t forget about my github: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*dyAAmcTV7pyB7BgS.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73029a2c73f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into Go: Implementing Classic Elevator Scheduling Algorithms — FCFS, SSTF, SCAN, and LOOK]]></title>
            <link>https://medium.com/@dmkaban62/diving-into-go-implementing-classic-elevator-scheduling-algorithms-fcfs-sstf-scan-and-look-4040c2de62f2?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4040c2de62f2</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 06:57:22 GMT</pubDate>
            <atom:updated>2024-12-24T06:57:22.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Diving into Go: Implementing Classic Elevator Scheduling Algorithms — FCFS, SSTF, SCAN, and LOOK</h3><p>Hi, dudes! Having spent a significant amount of time working with Go, I decided to take on an exciting challenge: implementing classic low-level design solutions in the language.</p><p>One of the key considerations when designing an elevator system is determining which floor to service next, especially when handling multiple requests simultaneously. Go’s clean syntax and robust performance make it a perfect fit for modeling such systems, so I embarked on creating basic implementations of FCFS (First Come First Serve), SSTF (Shortest Seek Time First), SCAN, and LOOK algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24uU40Vk6U1nw-Su6bWDkg.jpeg" /></figure><h3>1. First Come First Serve (FCFS)</h3><p>I started with the simplest approach: service requests in the order they’re received. It’s easy to implement but can be inefficient if the requests are spread out across floors, leading to more travel time.</p><pre>func FCFS(currentFloor int, requests []int) []int {<br>    path := []int{}<br>    for _, floor := range requests {<br>        path = append(path, floor)<br>    }<br>    return path<br>}</pre><p>In FCFS, the elevator simply moves to each requested floor in the given order.</p><h3>2. Shortest Seek Time First (SSTF)</h3><p>SSTF tries to minimize travel by choosing the closest requested floor next. This reduces travel time but can lead to “starvation” for far-off requests if new closer requests keep coming.</p><pre>func SSTF(currentFloor int, requests []int) []int {<br>    path := []int{}<br>    remaining := append([]int{}, requests...)<br><br>    for len(remaining) &gt; 0 {<br>        closestIdx := 0<br>        minDistance := abs(currentFloor - remaining[0])<br><br>        for i, floor := range remaining {<br>            distance := abs(currentFloor - floor)<br>            if distance &lt; minDistance {<br>                closestIdx = i<br>                minDistance = distance<br>            }<br>        }<br><br>        currentFloor = remaining[closestIdx]<br>        path = append(path, currentFloor)<br>        remaining = append(remaining[:closestIdx], remaining[closestIdx+1:]...)<br>    }<br>    return path<br>}<br><br>func abs(x int) int {<br>    if x &lt; 0 {<br>        return -x<br>    }<br>    return x<br>}</pre><p>This function finds the closest floor to the current floor each time, updating the elevator’s position after each move.</p><h3>3. SCAN (Elevator Algorithm)</h3><p>In SCAN, the elevator moves in one direction, servicing all requests in that direction until it reaches the end, then reverses. This approach is more fair than SSTF because it reduces starvation.</p><pre>func SCAN(currentFloor, maxFloor int, requests []int) []int {<br>    path := []int{}<br>    up := []int{}<br>    down := []int{}<br><br>    for _, floor := range requests {<br>        if floor &gt;= currentFloor {<br>            up = append(up, floor)<br>        } else {<br>            down = append(down, floor)<br>        }<br>    }<br><br>    sort.Ints(up)<br>    sort.Sort(sort.Reverse(sort.IntSlice(down)))<br><br>    path = append(path, up...)<br>    path = append(path, down...)<br>    return path<br>}</pre><p>This function splits requests into floors above and below the current position. It serves all floors upwards, then downwards.</p><h3>4. LOOK</h3><p>LOOK is a slight variation of SCAN. Instead of going all the way to the end, the elevator reverses direction at the last request in each direction. It saves time by stopping where the requests end, not at the physical limits.</p><pre>func LOOK(currentFloor int, requests []int) []int {<br>    path := []int{}<br>    up := []int{}<br>    down := []int{}<br><br>    for _, floor := range requests {<br>        if floor &gt;= currentFloor {<br>            up = append(up, floor)<br>        } else {<br>            down = append(down, floor)<br>        }<br>    }<br><br>    sort.Ints(up)<br>    sort.Sort(sort.Reverse(sort.IntSlice(down)))<br><br>    path = append(path, up...)<br>    path = append(path, down...)<br>    return path<br>}</pre><p>Similar to SCAN, this approach only moves as far as the last request in each direction.</p><p>Each algorithm has its trade-offs:</p><ul><li><strong>FCFS</strong>: Simple but can be inefficient.</li><li><strong>SSTF</strong>: Optimizes for closest floors but can starve far-off requests.</li><li><strong>SCAN</strong>: Fairer and efficient, minimizing direction changes.</li><li><strong>LOOK</strong>: Saves additional time by stopping at the last request.</li></ul><p>The right choice depends on the specific requirements for efficiency, fairness, and response time in the system.</p><p>For full implementation using LOOK algorithm, refer to my <a href="https://github.com/DmitriiKumancev/low-level-design-systems">github repo</a>:<br><a href="https://github.com/DmitriiKumancev/low-level-design-systems">https://github.com/DmitriiKumancev/low-level-design-systems</a></p><blockquote><strong><em>That’s it! I hope my article was interesting and informative for you 😎😜</em></strong></blockquote><p><strong><em>Don’t forget about my github: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*st8RkbZBKfqMw9J4.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4040c2de62f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Security: Best Practices, Configurations, and Real-Life Scenarios]]></title>
            <link>https://blog.devops.dev/docker-security-best-practices-configurations-and-real-life-scenarios-93b564a77ff1?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/93b564a77ff1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 12:41:20 GMT</pubDate>
            <atom:updated>2024-11-18T17:32:54.952Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, dudes! Docker security is essential in protecting containerized applications from vulnerabilities and threats that can arise from misconfigurations or malicious activity. This article will walk through Docker security fundamentals, common threats, and best practices with real-world examples to ensure secure containerized environments.</p><p><a href="https://dev.to/i_am_vesh/docker-day-1-4i3c"><em>(Here you can read a block of articles from the author, to whom I am very grateful for sharing this knowledge)</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*E8IgOSkMTpBRs0w0-Zsx2g.gif" /></figure><h3>Table of Contents:</h3><ol><li><strong>Understanding Docker Security</strong></li><li><strong>Docker Threat Landscape</strong></li><li><strong>Securing the Docker Host</strong></li><li><strong>Configuring Docker Daemon Security</strong></li><li><strong>Securing Docker Images</strong></li><li><strong>Protecting Containers at Runtime</strong></li><li><strong>Network Security for Docker Containers</strong></li><li><strong>Monitoring and Logging for Docker Security</strong></li><li><strong>Real-World Scenarios and Examples</strong></li><li><strong>Conclusion</strong></li></ol><h3>1. Understanding Docker Security</h3><p>Docker is designed with security features that provide isolation, resource limits, and access controls; however, it shares the underlying host OS kernel, which opens potential vulnerabilities. Proper Docker security is achieved by securing the <strong>Docker daemon</strong>, <strong>container images</strong>, <strong>network</strong>, and <strong>host system</strong>.</p><h3>2. Docker Threat Landscape</h3><p>The main security threats to Docker environments include:</p><ul><li><strong>Image Vulnerabilities</strong>: Malicious or outdated images with vulnerabilities.</li><li><strong>Insecure Configurations</strong>: Misconfigured Docker files, weak authentication, and unencrypted communications.</li><li><strong>Network Exposure</strong>: Exposing sensitive data through open ports and insecure network configurations.</li><li><strong>Privilege Escalation</strong>: Containers running with root privileges, allowing greater access to the host.</li><li><strong>Runtime Security Threats</strong>: Unauthorized access or resource overconsumption during container runtime.</li></ul><h3>3. Securing the Docker Host</h3><p>Securing the Docker host is critical since containers share the host kernel.</p><h4>Best Practices:</h4><ul><li><strong>Operating System Hardening</strong>: Run a minimal Linux distribution optimized for Docker (e.g., Alpine Linux).</li><li><strong>Regular Patching</strong>: Keep the OS and Docker software up-to-date to patch known vulnerabilities.</li><li><strong>Restrict Access</strong>: Only allow authorized users to run Docker commands by managing Docker groups carefully.</li><li><strong>Resource Limits</strong>: Use resource quotas (cpu, memory, etc.) to prevent resource exhaustion attacks.</li></ul><h4>Example:</h4><ul><li>Limit CPU and memory usage for a container by using:</li></ul><pre>docker run -d --name myapp --cpus=&quot;1.0&quot; --memory=&quot;512m&quot; myappimage</pre><h3>4. Configuring Docker Daemon Security</h3><p>The Docker daemon is the core service managing containers on a host and should be securely configured.</p><h4>Key Security Configurations:</h4><ul><li><strong>Seccomp Profile</strong>: Use Seccomp (Secure Computing Mode) to restrict system calls that the container can execute, reducing the risk of kernel attacks.</li></ul><pre>docker run --security-opt seccomp=/path/to/seccomp-profile.json myappimage</pre><ul><li><strong>AppArmor</strong>: AppArmor provides an additional layer of security by limiting access to system resources.</li></ul><pre>docker run --security-opt apparmor=my_profile myappimage</pre><ul><li><strong>TLS Encryption</strong>: Configure the Docker daemon to use TLS to secure communications with the Docker client.</li></ul><pre>{<br>    &quot;tls&quot;: true,<br>    &quot;tlscert&quot;: &quot;/path/to/cert.pem&quot;,<br>    &quot;tlskey&quot;: &quot;/path/to/key.pem&quot;,<br>    &quot;tlsverify&quot;: true<br>  }</pre><h4>Example Scenario:</h4><p>If you have Docker deployed on cloud servers, enforcing TLS ensures secure communication between your local machine and the cloud-based Docker daemon, protecting against man-in-the-middle attacks.</p><h3>5. Securing Docker Images</h3><p>Docker images are often a source of vulnerabilities. Securing images is essential for preventing malicious code from entering the environment.</p><h4>Best Practices:</h4><ul><li><strong>Use Official Images</strong>: Official images from Docker Hub are vetted and frequently updated.</li><li><strong>Minimize Image Size</strong>: Reduce the attack surface by using minimal base images, such as <strong>Alpine Linux</strong>.</li><li><strong>Scan Images for Vulnerabilities</strong>: Use tools like <strong>Trivy</strong>, <strong>Anchore</strong>, or <strong>Clair</strong> to detect vulnerabilities within images.</li></ul><pre>trivy image myappimage</pre><ul><li><strong>Avoid Using Latest Tags</strong>: Use specific version tags instead of latest to ensure predictable, secure deployments.</li></ul><h4>Example:</h4><ul><li>Create a Dockerfile with a minimal base image:</li></ul><pre>FROM alpine:3.12<br>  RUN apk add --no-cache python3<br>  COPY . /app<br>  WORKDIR /app<br>  CMD [&quot;python3&quot;, &quot;app.py&quot;]</pre><h3>6. Protecting Containers at Runtim</h3><p>Runtime security ensures that your containers are not compromised once they are deployed.</p><h4>Key Practices:</h4><ul><li><strong>Run as Non-Root</strong>: Always run containers with a non-root user to prevent privilege escalation.</li></ul><pre>FROM ubuntu<br>  RUN useradd -u 1001 myuser<br>  USER myuser</pre><ul><li><strong>Read-Only Filesystem</strong>: Run containers with a read-only filesystem to prevent unauthorized file changes.</li></ul><pre>docker run -d --read-only myappimage</pre><ul><li><strong>Limit Capabilities</strong>: Restrict containers to only the capabilities they need. For example:</li></ul><pre>docker run --cap-drop all --cap-add CHOWN myappimage</pre><h4>Example:</h4><p>To ensure a containerized app doesn’t modify its file system, use the read-only flag, preventing any changes during runtime.</p><h3>7. Network Security for Docker Containers</h3><p>Docker networking configuration impacts the security of how containers communicate with each other and the outside world.</p><h4>Network Security Strategies:</h4><ul><li><strong>Isolate Containers Using Custom Networks</strong>: Avoid using the default network and create custom bridge networks to isolate containers.</li></ul><pre>docker network create --driver bridge mynetwork</pre><ul><li><strong>Limit Exposed Ports</strong>: Only expose necessary ports, and avoid --publish-all.</li></ul><pre>docker run -d -p 8080:80 myappimage</pre><ul><li><strong>Use Internal Networks</strong>: Use Docker’s internal network for backend services that don’t need external access.</li></ul><pre>docker network create --internal myinternalnetwork</pre><h4>Example:</h4><p>For a web application with a frontend and backend, put the backend in an internal network to limit access to the frontend only, enhancing security.</p><h3>8. Monitoring and Logging for Docker Security</h3><p>Monitoring and logging are essential for detecting suspicious activity and ensuring compliance.</p><h4>Tools and Techniques:</h4><ul><li><strong>Docker Audit Logging</strong>: Enable audit logging for Docker to track commands and actions.</li><li><strong>Centralized Logging with ELK</strong>: Use <strong>Elasticsearch, Logstash, Kibana (ELK)</strong> to aggregate logs from multiple containers.</li><li><strong>Docker Stats and Resource Monitoring</strong>: Regularly monitor container resource usage to detect anomalies.</li></ul><pre>docker stats</pre><ul><li><strong>Security Event Monitoring</strong>: Use tools like <strong>Falco</strong> to monitor security events within your containers.</li></ul><h4>Example:</h4><p>Use Falco to detect unusual behavior, such as a shell being spawned in a container:</p><pre>falco -r /etc/falco/falco_rules.yaml -o json</pre><h3>9. Real-World Scenarios and Examples</h3><h4>Scenario 1: Secure Application Deployment with Minimal Images and User Restrictions</h4><ul><li><strong>Requirement</strong>: Deploy a Python app that’s accessible only on specific ports and needs no root permissions.</li><li><strong>Solution</strong>: Use a minimal image (Alpine), add only necessary packages, run as a non-root user, and limit the app to read-only access.</li><li><strong>Dockerfile</strong>:</li></ul><pre>FROM python:3.9-alpine<br>  RUN adduser -D myuser<br>  USER myuser<br>  COPY . /app<br>  WORKDIR /app<br>  CMD [&quot;python3&quot;, &quot;app.py&quot;]</pre><h4>Scenario 2: Multi-Tier Web Application with Internal Networking and Enforced Capabilities</h4><ul><li><strong>Requirement</strong>: Deploy a web application with a frontend accessible publicly and a backend accessible only internally.</li><li><strong>Solution</strong>: Create custom networks, place the backend on an internal network, and apply capability restrictions.</li></ul><pre># Create networks<br>  docker network create frontend_network<br>  docker network create --internal backend_network<br>  # Run frontend<br>  docker run -d --network frontend_network -p 80:80 frontend_image<br>  # Run backend<br>  docker run -d --network backend_network backend_image</pre><h4>Scenario 3: Scanning and Continuous Monitoring for Container Security</h4><ul><li><strong>Requirement</strong>: Deploy an application in a production environment with continuous scanning and monitoring.</li><li><strong>Solution</strong>: Integrate <strong>Trivy</strong> for vulnerability scanning before deployment and use <strong>Falco</strong> to monitor runtime security.</li></ul><pre># Scan image<br>  trivy image myappimage<br>  # Run Falco for monitoring<br>  falco -r /etc/falco/falco_rules.yaml</pre><h3>10. Conclusion</h3><p>Securing Docker involves a multi-layered approach that includes securing the host, Docker daemon, images, and network, as well as implementing runtime protections. By using best practices like running containers as non-root users, limiting network exposure, and leveraging tools like <strong>Trivy</strong> and <strong>Falco</strong> for vulnerability scanning and monitoring, you can build robust defenses around your containerized applications. Following these practices not only mitigates security risks but also aligns with industry standards, helping ensure a secure, compliant, and resilient container environment.</p><blockquote><strong><em>That’s it! I hope my article was interesting and informative for you 😎😜</em></strong></blockquote><p><strong><em>Don’t forget about my github: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*YucLTbBSkpjP4LtC.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93b564a77ff1" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/docker-security-best-practices-configurations-and-real-life-scenarios-93b564a77ff1">Docker Security: Best Practices, Configurations, and Real-Life Scenarios</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accelerate your database: 7 proven methods for scaling and optimization]]></title>
            <link>https://medium.com/@dmkaban62/accelerate-your-database-7-proven-methods-for-scaling-and-optimization-b2fc84411f98?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2fc84411f98</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 20:28:27 GMT</pubDate>
            <atom:updated>2024-08-16T20:28:27.779Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi friends!<br>Scaling improves performance and enhances the reliability of data storage systems by optimizing resource utilization and load distribution. In this article, I’ll look at seven effective methods for scaling and optimizing your database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nd__RsvqyQQeDiEdUz3c2w.jpeg" /></figure><ol><li><strong>Indexing</strong><br>Indexing in databases functions like a book’s table of contents — it allows you to quickly find and retrieve specific information without scanning the entire database for each individual record.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*9Rs1ttJAxrVhSZta75lNWg.png" /></figure><p><strong>Advantages:</strong></p><ul><li>Speeds up queries.</li><li>Reduces resource usage.</li><li>Increases concurrency.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Requires additional disk space for each indexed column.</li><li>Increases write overhead due to index updates.</li></ul><p><strong>2. Materialized Views</strong><br>A materialized view is a snapshot of the result of a query that is stored separately from the underlying data and maintained independently. It’s akin to a summary or abstract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*CtcCFw6K27kneOS6JMZVSw.png" /></figure><p><strong>Advantages:</strong></p><ul><li>Eliminates the need to perform complex and time-consuming queries in the user query stream.</li><li>Reduces load.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Requires additional storage space for the views.</li><li>Slower update times and potential data inconsistency in the view.</li></ul><p><strong>3. Denormalization</strong><br>Denormalization involves duplicating data across multiple tables to optimize query performance. For instance, imagine having two tables: one for customers and another for orders. Under normal circumstances, following data normalization rules (which aim to avoid data duplication), the Orders table would only reference the corresponding customer from the Customers table. To retrieve order details along with customer information, you’d need to perform a join operation on these tables.</p><p>As the number of orders grows, this join operation can become a performance bottleneck, requiring additional computation and processing time. Denormalization helps by deliberately duplicating data across different tables to improve query performance. In our example, you could add a CustomerName field directly to the Orders table. This allows you to obtain all the necessary order information, including the customer’s name, from a single table without performing a join operation. This significantly speeds up query execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*i35dphO-vauRxRL5CX1DYw.png" /></figure><p><strong>Advantages:</strong></p><ul><li>Faster queries.</li><li>Reduced overhead.</li><li>Accelerated read operations.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Data redundancy.</li><li>Complex updates due to the need to synchronize redundant data across multiple tables.</li><li>Potential inconsistency.</li></ul><p><strong>4. Vertical Scaling</strong><br>Vertical scaling involves upgrading the server’s hardware resources — installing more powerful CPUs, adding more RAM, or replacing outdated HDDs with SSDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*sKbnx8_5L3gRX6xIiLIhQg.png" /></figure><p><strong>Advantages:</strong></p><ul><li>Improved performance.</li><li>Simplified management.</li><li>Reduced latency.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>There are limits to vertical scaling, including cost constraints.</li><li>Server failure can lead to database downtime.</li></ul><p><strong>5. Caching</strong><br>Caching involves storing frequently requested data in a high-speed storage layer, separate from the main database:</p><p>When an application requests data, it first checks the cache. If the data is in the cache, it is quickly retrieved without querying the database. If the data isn’t in the cache, the application fetches it from the database and stores a copy in the cache for future requests. Caching is particularly useful for data that rarely changes but is frequently requested, as it avoids frequent and resource-intensive database queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*SZOjuhMLKiU2G08jmEQG0g.png" /></figure><p><strong>Advantages:</strong></p><ul><li>Reduces database load.</li><li>Enhances read performance.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Additional complexity in implementing a caching strategy.</li><li>Risk of serving outdated data to clients.</li></ul><p><strong>6. Replication</strong><br>Replication involves creating and maintaining multiple copies of data on different servers or nodes. This technique ensures high availability and fault tolerance for the database. In a typical leader-follower replication model, one node is designated as the leader, while the others are followers:</p><p>The leader handles all write operations, ensuring data consistency and integrity. When data changes or is added to the leader’s database, these changes are automatically propagated to the follower nodes. The leader can also handle critical read operations requiring a high degree of consistency. Followers are usually used for handling read requests to distribute the load and improve system performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*VaHkgtFWVJ4jGsGndZQdlw.png" /></figure><p><strong>Advantages:</strong></p><ul><li>Enhanced read performance.</li><li>High availability, even if several follower nodes fail.</li><li>Horizontal load distribution.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Introduces some latency in data synchronization.</li><li>Implementation complexity.</li></ul><p><strong>7. Sharding</strong><br>Sharding is a technique that divides a large database into smaller, more manageable units called shards. The primary sharding strategies include:</p><p>Sharding based on a range of shard key values. Hash sharding — where a hash function is applied to the shard key to determine the target shard. Directory-based sharding — where a separate table is maintained to map shard keys to corresponding shards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*JsNMVEvuSVcS7ovtj5j1JQ.png" /></figure><p><strong>Advantages:</strong></p><ul><li>Enables horizontal database scaling.</li><li>Queries and write operations are processed in parallel.</li><li>Lower hardware costs compared to vertical scaling.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Adds additional complexity.</li><li>Rebalancing data between shards can be complex and time-consuming.</li><li>Merging data across shards can become a non-trivial task.</li></ul><blockquote><strong><em>That’s it! I hope my article was interesting and informative for you 😎😜</em></strong></blockquote><p><strong><em>Don’t forget about my github: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*Oxyx5CULMUN6PnYIhUxuPA.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2fc84411f98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Free CPU Gains with Go’s Profile Guided Optimization]]></title>
            <link>https://medium.com/@dmkaban62/unlocking-free-cpu-gains-with-gos-profile-guided-optimization-c85631a91d90?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c85631a91d90</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 17:36:55 GMT</pubDate>
            <atom:updated>2024-06-30T17:36:55.282Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="https://blog.cloudflare.com/author/colin">Colin Douch</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*K71m-jOTbM5D8U0V732LZQ.png" /></figure><p>Hello my droogs! I recently came across an incredibly insightful article by Colin Douch that delves into optimizing CPU usage with Go’s Profile Guided Optimization (PGO). You can find Colin’s original piece <a href="https://blog.cloudflare.com/reclaiming-cpu-for-free-with-pgo/">here</a>. Inspired by his work, I wanted to share a summary and paraphrase of his findings to help you understand how PGO can significantly boost performance in Go applications.</p><h3>Introduction to Profile Guided Optimization (PGO)</h3><p>Go version 1.20 introduced PGO support, enabling the Go compiler to optimize based on real-world system behavior. At Cloudflare, the Observability Team oversees several Go-based services utilizing thousands of cores globally. Even modest savings of 2–7% in CPU usage can dramatically decrease our CPU footprint, allowing more resources to serve customer requests and enhancing overall customer experience.</p><h3>How Does PGO Work?</h3><p>PGO isn’t unique to Go; it’s a technique used to optimize generated assembly based on production CPU profiles. This optimization includes inlining frequently used functions, improving branch predictions, and rearranging code to minimize CPU cache swaps.</p><h4>The PGO Process</h4><ol><li><strong>Compile a Non-PGO Binary:</strong> Deploy this initial binary to production.</li><li><strong>Collect CPU Profiles:</strong> Gather CPU profiles from the production binary, which capture where the CPU spends the most time.</li><li><strong>Compile a PGO Binary:</strong> Use the collected profiles to guide the compiler in optimizing the program.</li></ol><p>This approach allows the compiler to make more informed decisions, such as inlining frequently called functions or unrolling loops, based on actual usage data rather than theoretical heuristics.</p><h3>Practical Application: The “Wshim” Service</h3><p>The Observability Team manages a service called “wshim,” which operates on every Cloudflare edge server as a telemetry push gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*7vIoGUmSpNoxKTdg8jAqPQ.png" /></figure><p>Given its extensive use, wshim demands significant CPU resources. Before implementing PGO, wshim consumed over 3000 cores globally. A 2% efficiency gain could free up 60 cores, enhancing network performance.</p><h4>Profiling and Optimization</h4><p>To gather representative profiles, we focused on high-usage servers during peak times, specifically from Tier 1 data centers. These are our largest and most heavily loaded facilities. We used Thanos infrastructure to identify top CPU users and fetched profiles using Go’s pprof tool. Here&#39;s a simplified version of our process:</p><pre># Fetch top CPU users for wshim<br>cloudflared access curl &quot;https://thanos/api/v1/query?query=topk%281000%2Cinstance%3Acontainer_cpu_time_seconds_total%3Arate2m%7Bapp_name%3D%22wshim.service%22%7D%29&amp;dedup=true&amp;partial_response=true&quot; --compressed | jq &#39;.data.result[].metric.instance&#39; -r &gt; instances_file<br><br># Collect CPU profiles<br>while read instance; do fetch-pprof $instance --port 8976 --seconds 30 &gt; &quot;profiles/${instance}.pprof&quot; &amp; done &lt; instances_file<br>wait $(jobs -p)<br><br># Merge profiles<br>go tool pprof -proto profiles/*.pprof &gt; profile.pprof</pre><p>This merged profile is committed to our repository:</p><pre># Example<br>~/cf-repos/wshim ± master<br>23/01/2024 10:49:08 AEDT❯ tree pgo<br>pgo<br>├── README.md<br>├── fetch-profiles.sh<br>└── profile.pprof</pre><p>and used to compile a PGO-optimized binary:</p><pre>build:<br>       go build -pgo ./pgo/profile.pprof -o /tmp/wshim ./cmd/wshim</pre><h3>Results and Analysis</h3><p>After deploying the PGO-optimized version of wshim, we analyzed CPU usage metrics to gauge savings. Comparing CPU usage immediately before and after deployment indicated a reduction of approximately 97 cores, a 3.5% decrease. Analyzing usage over the following week showed an average reduction of 71 cores compared to the week prior.</p><h3>Future Directions</h3><p>Our initial success with PGO demonstrates its potential to reclaim significant CPU resources without code changes. Moving forward, we aim to:</p><ul><li>Automate profile collection using continuous profiling</li><li>Refine the two-step deployment process</li><li>Improve profiling sample techniques</li><li>Explore further optimizations with BOLT and other Link Time Optimization (LTO) methods</li></ul><p>Thank you for reading! I hope this overview helps you understand the benefits and implementation of PGO in Go applications. For a deeper dive, check out Colin Douch’s original article <a href="https://blog.cloudflare.com/reclaiming-cpu-for-free-with-pgo/">here</a> and check out the <a href="https://www.youtube.com/watch?v=FwzE5Sdhhdw">Google report</a>.</p><p><strong><em>Don’t forget about my github: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*I4Ht5gSTOwIR4s4u.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c85631a91d90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go as a platform]]></title>
            <link>https://medium.com/@dmkaban62/go-as-a-platform-b3cbc9c4cd2c?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3cbc9c4cd2c</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 17:42:34 GMT</pubDate>
            <atom:updated>2024-06-28T17:42:34.471Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>By </strong><a href="https://eltonminetto.dev/"><strong>Elton Minetto</strong></a></p><p><em>Thanks to the Google Developer Experts program, I had the privilege of attending Google I/O in Mountain View, California, this past May. Among the many enlightening sessions, one particularly stood out: “Boost Performance of Go Applications with Profile-Guided Optimization.” You can find this session on </em><a href="https://www.youtube.com/watch?v=FwzE5Sdhhdw"><em>YouTube</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*XoOl279tx7M6pXc1v-zctg.png" /></figure><p>While Profile-Guided Optimization (PGO) is undoubtedly one of Go’s most thrilling features, what truly captivated me was the session’s introduction by Cameron Balahan, a Group Product Manager at Google Cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*aJWsurAKfrRU8T7sJSeXtg.png" /></figure><h3>The “DevOps Life Cycle” and Go’s Strengths</h3><p>Cameron began by discussing the “DevOps Life Cycle” and went on to emphasize Go’s strengths in three key areas:</p><ol><li><strong>Development Speed</strong></li><li><strong>Security</strong></li><li><strong>Performance</strong></li></ol><p>Here’s a closer look at each of these aspects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VW2K566JW-iPl4gidFDCQg.png" /></figure><h4>Development Speed</h4><ul><li><strong>Easy Concurrency:</strong> Go’s goroutines and channels simplify concurrent programming.</li><li><strong>IDE Integrations:</strong> Excellent IDEs like JetBrains’ GoLand and Visual Studio Code with Go plugins enhance productivity.</li><li><strong>Dependency Management:</strong> The built-in toolset for dependency management, including commands like go get and go mod tidy, streamlines project setup.</li><li><strong>Static Binaries:</strong> Simplifies deployment with self-contained executables.</li><li><strong>Delve Debugger:</strong> Integrated debugger in IDEs accelerates development and maintenance.</li><li><strong>Built-in Test Framework:</strong> Facilitates techniques like TDD with a standard library for testing.</li><li><strong>Cross-compilation:</strong> Easily generates binaries for various platforms from macOS.</li><li><strong>Built-in Formatting:</strong> The included linter ensures consistent code formatting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yrPN6F6xBc75rtQKxqI8WQ.png" /></figure><h4>Security</h4><ul><li><strong>Module Mirror Checksum DB:</strong> Ensures the authenticity of modules used as dependencies.</li><li><strong>Memory Safe Code:</strong> Prevents bugs related to memory usage.</li><li><strong>Compatibility Promise:</strong> Guarantees long-term stability, avoiding major refactorings like those from PHP 4 to 5 or Python 2 to 3.</li><li><strong>Vulnerability Scanning:</strong> The govulncheck tool helps identify and address vulnerabilities.</li><li><strong>Built-in Fuzz Testing:</strong> Enhances test coverage and code quality with arbitrary value testing.</li><li><strong>SBOM Generation:</strong> Provides a detailed inventory of software components and dependencies.</li><li><strong>Source Code Analysis:</strong> Supported by tools like Sonar and open-source projects like golangci-lint.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7MntY0TiM6SakgSStLmyQ.png" /></figure><h4>Performance</h4><ul><li><strong>Rich Standard Library:</strong> Comprehensive native library covering HTTP, tests, JSON, data structures, etc.</li><li><strong>Built-in Profiling:</strong> Features like pprof for performance analysis.</li><li><strong>Runtime Tracing:</strong> Improved tracing for detailed application behavior analysis.</li><li><strong>Self-tuning GC:</strong> Advanced Garbage Collector for optimized performance.</li><li><strong>Dynamic Race Detector:</strong> Detects issues early in development and testing.</li><li><strong>Profile-guided Optimization:</strong> Reduces resource consumption, detailed in the aforementioned session.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVQ__0XAhYfwQqY9sHh9Kg.png" /></figure><h3>Conclusion</h3><p>This session provided a concise overview of Go’s ecosystem and its benefits. It’s clear why many developers are drawn to Go. What are your thoughts on this perspective? Have you experienced these benefits firsthand?</p><p><em>The original content was inspired by </em><a href="https://eltonminetto.dev/en/post/2024-06-12-go-is-a-plataform/"><em>Elton Minetto’s</em></a><em> reflections on the Google I/O session.</em></p><blockquote><strong><em>That’s it! I hope my article was interesting and informative for you 😎😜</em></strong></blockquote><p><strong><em>Don’t forget about my github: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*Yc9LUlzKCD4x3Jqq.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3cbc9c4cd2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced SQL: Secrets of the Pros]]></title>
            <link>https://medium.com/@dmkaban62/advanced-sql-secrets-of-the-pros-c13b9bb7d719?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c13b9bb7d719</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 13:32:01 GMT</pubDate>
            <atom:updated>2024-06-27T13:35:06.342Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring advanced query optimization strategies, complex join types, and the intricacies of using SELECT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRYMlwEw4_m7dm50cfbhXA.jpeg" /></figure><h3>Advanced SQL: Secrets of the Pros</h3><p>Mastering the following methods will enable you to:</p><ul><li>Craft complex and efficient queries.</li><li>Optimize database performance.</li></ul><h3>Advanced Query Optimization Techniques</h3><p>Optimizing SQL queries is a fundamental skill for any database administrator and backend developer. Advanced optimization goes beyond indexing and query refactoring. Here are methods to make your queries truly efficient.</p><h4>1. Query Execution Plan</h4><p>The query execution plan is crucial for optimization as it shows how the SQL engine executes the query and highlights problematic fragments.</p><ul><li><strong>EXPLAIN</strong>: Provides information on how the query will be executed, allowing identification of inefficient sections:</li></ul><pre>EXPLAIN SELECT column1, column2 FROM table_name WHERE condition;</pre><ul><li><strong>ANALYZE</strong>: Used with EXPLAIN, it executes the query and provides execution time statistics, helping to assess performance:</li></ul><pre>EXPLAIN ANALYZE SELECT column1, column2 FROM table_name WHERE condition;</pre><h4>2. Subquery Optimization</h4><p>In some cases, subqueries can be replaced with more efficient joins or common table expressions (CTEs) with the WITH operator.</p><ul><li><strong>Replacing Subqueries with Joins</strong>:</li></ul><pre>-- Subquery <br>SELECT * FROM table1 WHERE column1 IN (SELECT column1 FROM table2);  <br>-- Equivalent Join <br>SELECT table1.* FROM table1 INNER JOIN table2 ON table1.column1 = table2.column1;</pre><ul><li><strong>Using Common Table Expressions</strong>:</li></ul><pre>WITH CTE AS (     <br>    SELECT column1, column2 FROM table_name WHERE condition <br>) <br>SELECT * FROM CTE WHERE another_condition;</pre><h4>3. Indexing Strategies</h4><p>Advanced indexing strategies include using composite indexes and covering indexes.</p><ul><li><strong>Composite Index</strong>: Includes multiple columns and can speed up queries that use filtering on these columns:</li></ul><pre>CREATE INDEX idx_composite ON table_name (column1, column2);</pre><ul><li><strong>Covering Index</strong>: Includes all columns retrieved by the query, significantly improving performance:</li></ul><pre>CREATE INDEX idx_covering ON table_name (column1, column2, column3);</pre><h4>4. Partitioning</h4><p>Partitioning (dividing a large table into smaller pieces) improves performance by reducing the volume of data to be scanned and simplifies data management, such as archiving or deletion.</p><ul><li><strong>Range Partitioning</strong>: Effective for data with a temporal or sequential key (dates or order numbers):</li></ul><pre>CREATE TABLE orders (     <br>    order_id INT,     <br>    order_date DATE,     <br>    ... <br>) PARTITION BY RANGE (order_date) (     <br>    PARTITION p0 VALUES LESS THAN (&#39;2024-01-01&#39;),     <br>    PARTITION p1 VALUES LESS THAN (&#39;2025-01-01&#39;),     <br>    ... <br>);</pre><ul><li><strong>Hash Partitioning</strong>: Distributes data across partitions using a hash function, improving performance for inserts and reads:</li></ul><pre>CREATE TABLE orders (     <br>    order_id INT,     <br>    order_date DATE,     <br>    ... ) PARTITION BY RANGE (order_date) (     PARTITION p0 VALUES LESS THAN (&#39;2024-01-01&#39;),     PARTITION p1 VALUES LESS THAN (&#39;2025-01-01&#39;),     ... );<br><br></pre><ul><li><strong>Hash Partitioning</strong>: Distributes data across partitions using a hash function, improving performance for inserts and reads:</li></ul><pre>CREATE TABLE users (<br>    user_id INT,<br>    username VARCHAR(255),<br>    ...<br>) PARTITION BY HASH (user_id) PARTITIONS 4;</pre><ul><li><strong>List Partitioning</strong>: Applied when column values belong to specific categories or groups:</li></ul><pre>CREATE TABLE sales (<br>    sale_id INT,<br>    region VARCHAR(255),<br>    ...<br>) PARTITION BY LIST (region) (<br>    PARTITION p0 VALUES IN (&#39;North&#39;, &#39;South&#39;),<br>    PARTITION p1 VALUES IN (&#39;East&#39;, &#39;West&#39;)<br>);</pre><h4>5. Materialized Views</h4><p>Materialized views store the result of a query physically and can be periodically refreshed. This improves performance for complex queries executed frequently.</p><ul><li><strong>Creating a Materialized View</strong>:</li></ul><pre>CREATE MATERIALIZED VIEW sales_summary AS<br>SELECT region, SUM(sales_amount) AS total_sales<br>FROM sales<br>GROUP BY region;</pre><ul><li><strong>Refreshing a Materialized View</strong>:</li></ul><pre>REFRESH MATERIALIZED VIEW sales_summary;</pre><p><strong>Materialized Views in MySQL</strong></p><p>MySQL does not have built-in support for materialized views, but this can be implemented manually using separate tables and scheduled tasks or triggers.</p><ul><li><strong>Using Tables and Scheduled Updates</strong>:</li></ul><pre>CREATE TABLE MaterializedActiveCustomers AS<br>SELECT CustomerID, CustomerName, ContactName, Country<br>FROM Customers<br>WHERE Status = &#39;Active&#39;;<br><br>CREATE EVENT UpdateMaterializedActiveCustomers<br>ON SCHEDULE EVERY 1 HOUR<br>DO<br>BEGIN<br>    DELETE FROM MaterializedActiveCustomers;<br>    INSERT INTO MaterializedActiveCustomers<br>    SELECT CustomerID, CustomerName, ContactName, Country<br>    FROM Customers<br>    WHERE Status = &#39;Active&#39;;<br>END;</pre><ul><li><strong>Using Triggers</strong>:</li></ul><pre>DELIMITER //<br><br>CREATE TRIGGER after_customer_insert<br>AFTER INSERT ON Customers<br>FOR EACH ROW<br>BEGIN<br>    IF NEW.Status = &#39;Active&#39; THEN<br>        INSERT INTO MaterializedActiveCustomers (CustomerID, CustomerName, ContactName, Country)<br>        VALUES (NEW.CustomerID, NEW.CustomerName, NEW.ContactName, NEW.Country);<br>    END IF;<br>END //<br><br>CREATE TRIGGER after_customer_update<br>AFTER UPDATE ON Customers<br>FOR EACH ROW<br>BEGIN<br>    IF OLD.Status = &#39;Active&#39; AND NEW.Status != &#39;Active&#39; THEN<br>        DELETE FROM MaterializedActiveCustomers WHERE CustomerID = OLD.CustomerID;<br>    ELSEIF NEW.Status = &#39;Active&#39; THEN<br>        REPLACE INTO MaterializedActiveCustomers (CustomerID, CustomerName, ContactName, Country)<br>        VALUES (NEW.CustomerID, NEW.CustomerName, NEW.ContactName, NEW.Country);<br>    END IF;<br>END //<br><br>CREATE TRIGGER after_customer_delete<br>AFTER DELETE ON Customers<br>FOR EACH ROW<br>BEGIN<br>    DELETE FROM MaterializedActiveCustomers WHERE CustomerID = OLD.CustomerID;<br>END //<br><br>DELIMITER ;sql</pre><h3>Advanced Join Techniques</h3><p>Basic joins allow you to retrieve data from multiple tables simultaneously, while advanced methods help perform more complex queries and additional manipulations.</p><h4>1. Self-Joins</h4><p>Self-joins allow combining rows from the same table using different aliases. In this example, employees and their managers’ names are retrieved:</p><pre>SELECT a.employee_id, a.name, b.name AS manager_name<br>FROM employees a<br>INNER JOIN employees b ON a.manager_id = b.employee_id;</pre><h4>2. Lateral Joins</h4><p>The LATERAL keyword allows subqueries to reference columns from previous tables listed in FROM. For each row from table1, this subquery retrieves one row from table2 where b.column1 = a.column1, ordered by b.column2 in descending order:</p><pre>SELECT a.*, b.*<br>FROM table1 a<br>LEFT JOIN LATERAL (<br>    SELECT *<br>    FROM table2 b<br>    WHERE b.column1 = a.column1<br>    ORDER BY b.column2 DESC<br>    LIMIT 1<br>) b ON TRUE; ко</pre><h4>3. Full Outer Joins with COALESCE</h4><p>This technique avoids NULL values in the result of a full outer join. The COALESCE function returns the first non-null value from the list:</p><pre>SELECT COALESCE(a.column1, b.column1) AS column1, a.column2, b.column2<br>FROM table1 a<br>FULL OUTER JOIN table2 b ON a.column1 = b.column1;</pre><h4>4. Advanced Join Filters</h4><p>For more precise filtering in joins, complex conditions can be applied. This example joins with an additional condition on a.date_column, filtering results by a date range:</p><pre>SELECT a.column1, b.column2<br>FROM table1 a<br>INNER JOIN table2 b ON a.column1 = b.column1 AND a.date_column BETWEEN &#39;2023-01-01&#39; AND &#39;2023-12-31&#39;;</pre><h4>5. Anti-Joins and Semi-Joins</h4><p>These join types are useful for exclusion and inclusion queries, respectively.</p><ul><li><strong>Anti-Join</strong>: Retrieves rows from the left table that have no matching rows in the right table:</li></ul><pre>SELECT a.*<br>FROM table1 a<br>LEFT JOIN table2 b ON a.column1 = b.column1<br>WHERE b.column1 IS NULL;</pre><ul><li><strong>Semi-Join</strong>: Retrieves rows from the left table for which there is one or more matching rows in the right table:</li></ul><pre>SELECT a.*<br>FROM table1 a<br>WHERE EXISTS (SELECT 1 FROM table2 b WHERE a.column1 = b.column1);</pre><h3>Advanced SELECT Techniques</h3><p>The capabilities of the SELECT statement can be extended with additional functions, helping solve the most complex data retrieval tasks.</p><h4>1. Window Functions</h4><p>Window functions perform calculations across a set of table rows related to the current row, providing powerful analytical capabilities.</p><ul><li><strong>Row Numbering</strong>:</li></ul><pre>SELECT column1, column2, ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY column2) AS row_num<br>FROM table_name;</pre><ul><li><strong>Running Total</strong>:</li></ul><pre>SELECT column1, column2, SUM(column2) OVER (ORDER BY column1) AS running_total<br>FROM table_name;</pre><ul><li><strong>Ranking</strong>:</li></ul><pre>SELECT column1, column2, RANK() OVER (PARTITION BY column1 ORDER BY column2) AS rank<br>FROM table_name;</pre><ul><li><strong>Moving Average</strong>:</li></ul><pre>SELECT column1, column2, AVG(column2) OVER (PARTITION BY column1 ORDER BY column2 ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS moving_avg<br>FROM table_name;</pre><h4>2. Recursive Common Table Expressions</h4><p>Recursive CTEs allow performing recursive queries, useful for working with hierarchical data:</p><pre>WITH RECURSIVE cte AS (<br>    SELECT column1, column2<br>    FROM table_name<br>    WHERE condition<br>    UNION ALL<br>    SELECT t.column1, t.column2<br>    FROM table_name t<br>    INNER JOIN cte ON t.column1 = cte.column1<br>)<br>SELECT * FROM cte;</pre><h4>3. JSON Functions</h4><p>Modern DBMSs often include functions for storing and querying JSON documents.</p><ul><li><strong>Extracting Values from JSON</strong>:</li></ul><pre>SELECT json_column-&gt;&gt;&#39;key&#39; AS value<br>FROM table_name;sql</pre><ul><li><strong>Aggregating into JSON</strong>:</li></ul><pre>SELECT json_agg(row_to_json(t))<br>FROM (SELECT column1, column2 FROM table_name) t;</pre><ul><li><strong>Updating JSON Data</strong>:</li></ul><pre>UPDATE table_name<br>SET json_column = jsonb_set(json_column, &#39;{key}&#39;, &#39;&quot;new_value&quot;&#39;, true)<br>WHERE condition;</pre><h4>4. Data Pivoting</h4><p>Pivoting transforms rows into columns, allowing reorganizing and summarizing data for reporting. CASE expressions are used for pivoting:</p><pre>SELECT<br>    category,<br>    SUM(CASE WHEN year = 2021 THEN sales ELSE 0 END) AS sales_2021,<br>    SUM(CASE WHEN year = 2022 THEN sales ELSE 0 END) AS sales_2022<br>FROM sales_data<br>GROUP BY category;</pre><h4>5. Dynamic SQL</h4><p>Dynamic SQL allows constructing SQL statements on the fly for executing complex queries.</p><ul><li><strong>Executing Dynamic SQL</strong>:</li></ul><pre>EXECUTE &#39;SELECT * FROM &#39; || table_name || &#39; WHERE &#39; || condition;</pre><ul><li><strong>Using Prepared Statements</strong>:</li></ul><pre>PREPARE stmt AS SELECT * FROM table_name WHERE column1 = $1;<br>EXECUTE stmt(&#39;value&#39;);</pre><h3>Conclusion</h3><p>Advanced SQL techniques enable you to:</p><ul><li>Solve the most complex data manipulation and retrieval tasks.</li><li>Ensure the efficient operation of applications handling large volumes of data.</li></ul><p>Understanding execution plans, using advanced joins, applying complex expressions with SELECT, and implementing indexing strategies are essential skills for any database professional: administrator, backend developer, or analyst. Integrating these techniques into your workflow will significantly improve the performance and scalability of complex applications using a database.</p><blockquote><strong><em>That’s it! I hope my article was interesting and informative for you 😎😜</em></strong></blockquote><p><strong><em>Don’t forget about my github: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*l_tAmGTalJu9vptvKEQTDw.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c13b9bb7d719" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SDK ChatGPT for Go]]></title>
            <link>https://medium.com/@dmkaban62/sdk-chatgpt-for-go-002be3cdbd60?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/002be3cdbd60</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 17:57:54 GMT</pubDate>
            <atom:updated>2023-12-01T17:57:54.514Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello gofers and beyond! Today I want to share with you the implementation of my ChatGpt sdk for Golang. I hope you like it.</p><blockquote><a href="https://github.com/DmitriiKumancev/chatgpt-go"><em>Link to the finished project (don’t forget the stars :3)</em></a></blockquote><p><a href="https://media.tenor.com/ASXv1wVe-wkAAAAC/koksal-koksal-baba.gif">We’re off!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nzjb-A5UDs0ryXVpe7EHrQ.png" /></figure><p><em>First you must log in to the ChatGPT website, find the cookies named </em><strong><em>cf_clearance</em></strong><em>, </em><strong><em>__Secure-next-auth.session-token</em></strong><em> and set their cookie values to no more than</em><strong><em> 2 hours.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ur3z3HjrJCcjBDBBDsyfiQ.png" /></figure><h4>1. Quick start</h4><p>install chatgpt-go sdk:</p><pre>go get -u github.com/chatgp/chatgpt-go</pre><h4>2. Working with SDKpackage main</h4><pre>import (<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>	&quot;time&quot;</pre><pre>	chatgpt &quot;github.com/chatgp/chatgpt-go&quot;<br>)</pre><pre>func main() {<br>	// new chatgpt client<br>	token := `copy-from-cookies`<br>	cfValue := &quot;copy-from-cookies&quot;</pre><pre>	cookies := []*http.Cookie{<br>		{<br>			Name:  &quot;__Secure-next-auth.session-token&quot;,<br>			Value: token,<br>		},<br>		{<br>			Name:  &quot;cf_clearance&quot;,<br>			Value: cfValue,<br>		},<br>	}</pre><pre>	cli := chatgpt.NewClient(<br>		chatgpt.WithDebug(true),<br>		chatgpt.WithTimeout(60*time.Second),<br>		chatgpt.WithCookies(cookies),<br>	)</pre><pre>	// chat in independent conversation<br>	message := &quot;say hello to me&quot;<br>	text, err := cli.GetChatText(message)<br>	if err != nil {<br>		log.Fatalf(&quot;get chat text failed: %v&quot;, err)<br>	}</pre><pre>	log.Printf(&quot;q: %s, a: %s\n&quot;, message, text.Content)<br>}</pre><h4>3. Communicating in an uninterrupted conversation package main</h4><pre>import (<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>	&quot;time&quot;</pre><pre>	chatgpt &quot;github.com/chatgp/chatgpt-go&quot;<br>)</pre><pre>func main() {<br>	// new chatgpt client<br>	token := `copy-from-cookies`<br>	cfValue := &quot;copy-from-cookies&quot;</pre><pre>	cookies := []*http.Cookie{<br>		{<br>			Name:  &quot;__Secure-next-auth.session-token&quot;,<br>			Value: token,<br>		},<br>		{<br>			Name:  &quot;cf_clearance&quot;,<br>			Value: cfValue,<br>		},<br>	}</pre><pre>	cli := chatgpt.NewClient(<br>		chatgpt.WithDebug(true),<br>		chatgpt.WithTimeout(60*time.Second),<br>		chatgpt.WithCookies(cookies),<br>	)</pre><pre>	// chat in continuous conversation</pre><pre>	// first message<br>	message := &quot;say hello to me&quot;<br>	text, err := cli.GetChatText(message)<br>	if err != nil {<br>		log.Fatalf(&quot;get chat text failed: %v&quot;, err)<br>	}</pre><pre>	log.Printf(&quot;q: %s, a: %s\n&quot;, message, text.Content)</pre><pre>	// continue conversation with new message<br>	conversationID := text.ConversationID<br>	parentMessage := text.MessageID<br>	newMessage := &quot;again&quot;</pre><pre>	newText, err := cli.GetChatText(newMessage, conversationID, parentMessage)<br>	if err != nil {<br>		log.Fatalf(&quot;get chat text failed: %v&quot;, err)<br>	}</pre><pre>	log.Printf(&quot;q: %s, a: %s\n&quot;, newMessage, newText.Content)<br>}</pre><h4>4. Get the content of the chat with the streampackage main</h4><pre>import (<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>	&quot;time&quot;</pre><pre>	chatgpt &quot;github.com/chatgp/chatgpt-go&quot;<br>)</pre><pre>func main() {<br>	// new chatgpt client<br>	token := `copy-from-cookies`<br>	cfValue := &quot;copy-from-cookies&quot;</pre><pre>	cookies := []*http.Cookie{<br>		{<br>			Name:  &quot;__Secure-next-auth.session-token&quot;,<br>			Value: token,<br>		},<br>		{<br>			Name:  &quot;cf_clearance&quot;,<br>			Value: cfValue,<br>		},<br>	}</pre><pre>	cli := chatgpt.NewClient(<br>		chatgpt.WithDebug(true),<br>		chatgpt.WithTimeout(60*time.Second),<br>		chatgpt.WithCookies(cookies),<br>	)</pre><pre>	message := &quot;say hello to me&quot;<br>	stream, err := cli.GetChatStream(message)<br>	if err != nil {<br>		log.Fatalf(&quot;get chat stream failed: %v\n&quot;, err)<br>	}</pre><pre>	var answer string<br>	for text := range stream.Stream {<br>		log.Printf(&quot;stream text: %s\n&quot;, text.Content)<br>		answer = text.Content<br>	}</pre><pre>	if stream.Err != nil {<br>		log.Fatalf(&quot;stream closed with error: %v\n&quot;, stream.Err)<br>	}</pre><pre>	log.Printf(&quot;q: %s, a: %s\n&quot;, message, answer)<br>}</pre><h4>Tests</h4><p>There are some tests in the examples folder, run the go test command and get the results as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-wgEqo8-cG_8qCXC.png" /><figcaption><em>get chat text</em></figcaption></figure><p><em>get the chat text in a continuous dialog</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ETFGJybpT_stox0Q.png" /></figure><p><em>retrieve chat text from the stream</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*6JQkqDwgWxs5zgd4.png" /></figure><blockquote><strong><em>That’s it! I hope my article was interesting and informative for you 😎😜</em></strong></blockquote><blockquote><strong><em>Don’t forget about my </em></strong><a href="https://github.com/DmitriiKumancev"><strong><em>github</em></strong></a><strong><em>: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/0*3or06AFlMCgeHYaf.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=002be3cdbd60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Become the richest programmer in your country]]></title>
            <link>https://medium.com/@dmkaban62/become-the-richest-programmer-in-your-country-bb0334bf96ae?source=rss-d1d30ee7a16f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb0334bf96ae</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dmitrii Kumancev]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 08:06:33 GMT</pubDate>
            <atom:updated>2023-11-29T08:06:33.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello friends! Today I want to tell you about how you can be successful, making the product that is needed in your country, on the example of the story of one successful man.</p><p><a href="https://media.tenor.com/ASXv1wVe-wkAAAAC/koksal-koksal-baba.gif">We’re off!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2GLdKaVlmJurTFGKIneHew.gif" /></figure><h4>First steps Ma Huateng in IT</h4><p>Huateng got a job in a company that was engaged in the promotion of telephone services. And Internet technologies opened up to him during a trip to the USA. There he noticed the ICQ messenger. In China, it was little used, as it was necessary to know English.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*5_xsC33bGvcxo4q2xpHpPQ.jpeg" /></figure><h4>From business trip to business</h4><p>Suddenly, Ma realized that it was possible to make a good fortune around the assimilation of ICQ in the Chinese market. Having shared the plan with friends and having collected the first capital, the company began productive work. And just a year later, a working prototype of the messenger appeared — QQ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*erlzpluwLSIH_oYIY9Owag.jpeg" /><figcaption>Mascot Qq Com Control By Tencent</figcaption></figure><h4>Take off! (Google yahoo!)</h4><p>It didn’t take long for Chinese citizens to get used to it quickly and start communicating in the new app. I was attracted by the simplicity of the interface and the emphasis on the experience of IT giants. Using effective methods of Google and Yahoo, Ma company was able to offer a really high-quality product to the Chinese market.</p><h4>Do what already works</h4><p>Ma wanted his new business products to complement each other, thereby providing even more benefits to end users, and not giving any chance to competitors. So, in 1999, the company released OICQ, designed for instant messaging, which remains popular to this day.</p><h4>And what’s next?</h4><p><strong><em>And then we continue to bend our line</em></strong></p><p>Having a sufficient cash reserve, Ma conceived something “new”, promising. His new brainchild was WeChat, which was developed for the needs of mobile devices. Still copying successful Western products, Ma created the Weixin messenger, which was very similar to Whatsapp, but kept the Chinese specifics. And, of course, you can add hundreds of monetization there for more profit: shopping, booking, tracking a fitness tracker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WPaHpHAKsp3lYQAAoAxug.png" /></figure><h4>What did it lead to?</h4><p><strong><em>Microsoft Tencent Google</em></strong></p><p>Only to success, Huateng brought the company to such a level that it was recognized as the most expensive in China can easily compete with IT giants like Microsoft or Google.</p><blockquote><strong><em>That’s it! I hope my article was interesting and informative for you 😎😜</em></strong></blockquote><blockquote><strong><em>Don’t forget about my </em></strong><a href="https://github.com/DmitriiKumancev"><strong><em>github</em></strong></a><strong><em>: </em></strong><a href="https://github.com/DmitriiKumancev">https://github.com/DmitriiKumancev</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/0*HS_1HQ8g_SrXP8hl.gif" /><figcaption>See you soon!❤️️</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb0334bf96ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>