Header image

Xử Lý Lỗi Theo Phong Cách Lập Trình Hàm Trong Kotlin Với Arrow-kt

07/04/2022

882

Xử Lý Lỗi Theo Phong Cách Lập Trình Hàm Trong Kotlin Với Arrow-kt

Bài viết này sẽ giới thiệu một số cách để xử lý lỗi trong Kotlin theo phong cách lập trình hàm sử dụng thư viện Arrow-kt. Những ví dụ được đưa ra sẽ theo thứ tự từ đơn giản đến phức tạp nhưng mạnh mẽ hơn.

Kotlin là gì?

Kotlin là một ngôn ngữ lập trình kiểu tĩnh, ban đầu được thiết kế để chạy trên máy ảo Java (JVM), sau này có thể biên dịch sang JavaScript và Native binaries sử dụng công nghệ LLVM. Kotlin có cú pháp hiện đại, ngắn gọn, an toàn và hỗ trợ cả lập trình hướng đối tượng (OOP)lập trình hàm (FP).

Arrow-kt là gì?

Arrow-kt (https://arrow-kt.io/) là một thư viện Typed Functional Programming trong Kotlin. Arrow cung cấp một ngôn ngữ chung của các interface và sự trừu tượng hóa trên các thư viện Kotlin. Nó bao gồm các kiểu dữ liệu phổ biến nhất như Option, Either, Validated, v.v … và các functional operator như traversecomputation blocks giúp cho người dùng viết các ứng dụng và thư viện pure FP dễ dàng hơn.

Setup

Trong file build.gradle.kts của root project, thêm mavenCentral vào danh sách:

allprojects {
    repositories {
        mavenCentral()
    }
}

Thêm dependency vào file build.gradle.kts của project:

val arrow_version = "1.0.1"
dependencies {
    implementation("io.arrow-kt:arrow-core:$arrow_version")
}

Pure function và exceptions

Pure function

Trong lập trình hàm, pure function là những function có hai tính chất:

  • Giá trị trả về chỉ phụ thuộc vào tham số truyền vào nó (tức là nếu cùng input thì cùng output).
  • Không tạo ra các side effect.

Side effect là những tác dụng xảy ra khi thực hiện một function mà không phải công dụng chính của nó. Ví dụ: ngoài việc trả về các giá trị, nó gây ra những tương tác thay đổi môi trường, thay đổi các biến toàn cục, thực hiện các hoạt động I/O như HTTP request, in dữ liệu ra console, đọc và ghi files Trong Kotlin, tất cả các function trả về Unit rất có thể tạo ra side effect. Đó là bởi vì giá trị trả về là Unit biểu thị “không có giá trị hữu ích được trả về”, điều này ngụ ý rằng function không làm gì khác ngoài việc thực hiện các side effect.

Một số ví dụ pure function trong Kotlin là những hàm toán học như sin, cos, max, …

Lợi ích của pure functions: dễ dàng combine, dễ dàng test, dễ dàng debug, dễ dàng parallelize, … Vì thế trong lập trình hàm, chúng ta sẽ cố gắng sử dụng nhiều pure functions nhất có thể, và tách biệt các phần pure và impure.

Exceptions

Kotlin có thể throwcatch các Exception tương tự như ngôn ngữ Java, JavaScript, C++,… Sử dụngtry { } catch(e) { } finally { } là cách xử lý lỗi phổ biến trong các ngôn ngữ lập trình mệnh lệnh.

Tuy nhiên việc throw và catch các Exception, chúng ta có thể thay đổi hành vi của function, khiến cho các function không còn pure nữa (catch Exception là một side effect). Ví dụ, một function catch hai Exception là ex1ex2 từ một function khác và tính toán kết quả, lúc đó kết quả đó sẽ phụ thuộc vào thứ tự thực thi của các câu lệnh, thậm chí có thể thay đổi giữa hai lần thực thi khác nhau của cùng một hệ thống.

Partial function

Ngoài ra, việc throw các Exception khiến cho các function trở thành một Partial function, tức là một function không hoàn toàn – không được xác định cho tất cả các giá trị input có thể có, bởi vì trong một số trường hợp, nó có thể không bao giờ trả về bất cứ thứ gì. Ví dụ, trong trường hợp một vòng lặp vô hạn hoặc nếu một Exception được throw.

Ví dụ: findUserById ở ví dụ dưới là một partial function.

@JvmInline
value class UserId(val value: String)

@JvmInline
value class Username(val value: String)

@JvmInline
value class PostId(val value: String)

data class User(
    val id: UserId,
    val username: Username,
    val postIds: List<PostId>
)

class UserException(message: String?, cause: Throwable?) : Exception(message, cause)

/**
 * @return an [User] if found or `null` otherwise.
 * @throws UserException if there is any error (eg. database error, connection error, ...)
 */
suspend fun findUserById(id: UserId): User? = TODO()

Đề làm cho findUserById trở thành một total function, chúng ta thay vì throw UserException, chúng ta có thể return nó như một giá trị, thay return type của findUserById thành UserResult.

sealed interface UserResult {
    data class Success(val user: User?) : UserResult
    data class Failure(val error: UserException) : UserResult
}

suspend fun findUserById(id: UserId): UserResult = TODO()

Các vấn đề với Exceptions

Exception có thể được xem như là những câu lệnh GOTO như trong C/C++, vì chúng làm gián đoạn luồng chương trình bằng cách quay lại nơi gọi nó. Các Exception không nhất quán, đặc biệt là khi trong lập trình Multithread, chúngta try...catch một function nhưng Exception được throw ở một Thread khác mà không thể catch nó được.

Một vấn đề khác là việc lạm dụng catch Exception: catch nhiều hơn những gì cần thiết và cả những Exception từ hệ thống như VirtualMachineError, OutOfMemoryError,…

try {
    doExceptionalStuff() //throws IllegalArgumentException
} catch (e: Throwable) {
    // too broad, `Throwable` matches a set of fatal exceptions and errors
    // a user may be unable to recover from:
    /*
    VirtualMachineError
    OutOfMemoryError
    ThreadDeath
    LinkageError
    InterruptedException
    ControlThrowable
    NotImplementedError
    */
}

Và cuối cùng, nhìn vào một signature của một function, chúng ta không thể biết được, nó sẽ throw ra Exception nào, ngoài việc đọc docs hay là đọc source code của nó, thay vào đó, chúng ta hay để signature của function đó biểu hiện rõ ràng những lỗi nào có thể xảy ra khi gọi function đó.

Vì vậy, để xử lý lỗi, chúng ta cần một type có thể được compose với nhau, và biểu thị một kết quả hợp lệ hoặc một lỗi. Những type đó là Discriminated union/ tagged union, trong Kotlin đó được triển khai thông qua sealed class/sealed interface/enum class. Chúng ta sẽ cùng tìm hiểu kotlin.Result được cung cấp bởi Kotlin Sdtlib từ version 1.3 , và sau đó là arrow.core.Either đến từ thư viện Arrow-kt.

Sử dụng kotlin.Result để xử lý lỗi

Chúng ta có thể sử dụng Result<T> như là một type để biểu thị: hoặc là giá trị thành công với type là T, hoặc là là một lỗi xảy ra với một một Throwable. Nếu theo cách hiểu đơn giản, Result<T> = T | Throwable.

Để tạo ra giá trị Result, ta có thể dụng các function có sẵn như

  • Result.success
  • Result.failure
  • runCatching (tương tự như try { } catch { }
    nhưng trả về Result).
suspend fun findUserByIdFromDb(id: String): UserDb? = TODO()

fun UserDb.toUser(): User = TODO()

suspend fun findUserById(id: UserId): Result<User?> = runCatching { findUserByIdFromDb(id.value)?.toUser() }

Chúng ta có thể kiểm tra Result là giá trị thành công hay không, thông qua hai property là isSuccessisFailure. Để thực hiện các hành động ứng với mỗi trường hợp của Result thông qua function onSuccessonFailure.

val userResult: Result<User?> = findUserById(UserId("#id"))
userResult.isSuccess
userResult.isFailure
userResult.onSuccess { u: User? -> println(u) }
userResult.onFailure { e: Throwable -> println(e) }

Để có thể lấy giá trị bên trong Result, chúng ta sử dụng các function getOr__. Sử dụng exceptionOrNull để truy cập giá trị Throwable bên trong nếu Result đại diện cho giá trị thất bại. Ngoài ra, còn có function fold có thể handle một trong hai case dễ dàng.

val userResult: Result<User?> = findUserById(UserId("#id"))

// Access value
userResult.getOrNull()
userResult.getOrThrow()
userResult.getOrDefault(defaultValue)
userResult.getOrElse { e: Throwable -> defaultValue(e) }

// Access Throwable
userResult.exceptionOrNull()

fun handleUser(u: User?) {}
fun handleError(e: Throwable) {
    when (e) {
        is UserException -> {
            // handle UserException
        }
        else -> {
            // handle other cases
        }
    }
}

userResult.fold(
    onSuccess = { handleUser(it) },
    onFailure = { handleError(it) }
)

Tuy nhiên, sức mạnh thực sự của Result nằm ở việc chain các hoạt động trên nó. Ví dụ: nếu bạn muốn truy cập một property của User:

val userResult: Result<User?> = findUserById(UserId("#id"))
val usernameNullableResult: Result<Username?> = userResult.map { it?.username }

Chú ý rằng, nếu việc gọi lambda truyền vào function map throw Exception, thì Exception đó sẽ bị throw ra ngoài. Nếu muốn Exception đó được catch và chuyển thành giá trị Result, sử dụng mapCatching để vừa map vừa catching.

val usernameResult: Result<Username> = userResult.map {
    checkNotNull(it?.username) { "user is null!" }
}

Một vấn đề đặt ra là làm sao để chain các Result mà phụ thuộc lẫn nhau

// (UserId) -> Result<User?>
suspend fun findUserById(id: UserId): Result<User?> = TODO()

// User -> List<Post>
suspend fun getPostsByUser(user: User): Result<List<Post>> = TODO()

// List<Post> -> Result<Unit>
suspend fun doSomethingWithPosts(posts: List<Post>): Result<Unit> = TODO()

Chúng ta tạo một function flatMap (mapflatten).

// Map and flatten
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> = mapCatching { transform(it).getOrThrow() }

// or
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> = map(transform).flatten()
inline fun <T> Result<Result<T>>.flatten(): Result<T> = getOrElse { Result.failure(it) }

Bằng việc sử dụng flatMap, chúng ta có thể chain các Result với nhau

val unitResult: Result<Unit> = findUserById(UserId("#id"))
    .flatMap { user: User? -> runCatching { checkNotNull(user) { "user is null!" } } }
    .flatMap { getPostsByUser(it) }
    .flatMap { doSomethingWithPosts(it) }

Thư viện Arrow-kt cũng cung cấp block result { ... } để có thể handle việc chain các Result với nhau, tránh một số trường hợp sử dụng quá nhiều các nested flatMap. Trong block result { ... }, sử dụng function bind() để lấy giá trị T từ Result<T>. Nếu bind được gọi trên một Result đại diện một lỗi, thì phần code ở phía dưới nó trong block result { ... } sẽ bị bỏ qua (cơ chế short-circuits).

import arrow.core.*

val unitResult: Result<Unit> = result { /*this: ResultEffect*/
    val userNullable: User? = findUserById(UserId("#id")).bind()
    val user: User = checkNotNull(userNullable) { "user is null!" }
    val posts: List<Post> = getPostsByUser(user).bind()
    doSomethingWithPosts(posts).bind()
}

Một số tình huống khác có thể yêu cầu các chiến lược xử lý lỗi phức tạp có thể bao gồm khôi phục hoặc báo cáo lỗi. Ví dụ, chúng ta fetch data từ remote server, nếu bị lỗi thì sẽ lấy data từ cache. Chúng ta có thể sử dụng 2 function recoverrecoverCatching,

class MyData(...)

fun getFromRemote(): MyData = TODO()
fun getFromCache(): MyData = TODO()

val result: Result<MyData> = runCatching { getFromRemote() }
    .recoverCatching { e: Throwable ->
        logger.error(e, "getFromRemote")
        getFromCache()
    }

Sử dụng Result là một cách tiếp cận này tốt hơn, tuy nhiên vấn đề là lỗi luôn luôn là một Throwable, ta phải đọc docs hoặc đọc source code của nó. Một vấn đề nữa là runCatching khi kết hợp với suspend function, nó sẽ catch mọi Throwable, kể cả kotlinx.coroutines.CancellationException, CancellationException là một Exception đặc biệt, được coroutines sử dụng để đảm bảo cơ chế cooperative cancellation (xem issues 1814 Kotlin/kotlinx.coroutines).

Một cách tiếp cận tốt hơn là sử dụng arrow.core.Either, khắc phục các nhược điểm của Result.

Sử dụng arrow.core.Either để xử lý lỗi

Chúng ta có thể sử dụng Either<L, R> như là một type để biểu thị: hoặc là giá trị Left(value: L) , hoặc là giá trị Right(value: R). Nếu theo cách hiểu đơn giản, Either<L, R> = L | R.

public sealed class Either<out A, out B> {
    public data class Left<out A> constructor(val value: A) : Either<A, Nothing>()
    public data class Right<out B> constructor(val value: B) : Either<Nothing, B>()
}

Trong đó, Left thường đại diện cho các giá trị lỗi, giá trị không mong muốn, và Right thường đại diện cho các giá trị thành công, giá trị mong muốn. Nhìn chung Either<L, R> tương tự với Result<T>, Result<T> chỉ tập trung vào type của giá trị thành công mà không quan tâm đến type của giá trị lỗi, và chúng ta có thể xem Result<R> ~= Either<Throwable, R>. Eitherright-biased, tức là các function như map, filter, flatMap, … sẽ theo nhánh Right, nhánh Left bị bỏ qua (được return trực tiếp mà không có hành động nào trên nó cả).

Để tạo ra giá trị Either, ta có thể dụng các function có sẵn như:

  • Left constructor, ví dụ: val e: Either<Int, Nothing> = Left(1)
  • Right constructor, ví dụ: val e: Either<Nothing, Int> = Right(1)
  • left extension function, ví dụ val e: Either<Int, Nothing> = 1.left().
  • right extension function, ví dụ val e: Either<Nothing, Int> = 1.right().
  • Either.catch functions, catch các Exceptions nhưng nó sẽ bỏ qua các fatal Exception
    như kotlinx.coroutines.CancellationException, VirtualMachineError, OutOfMemoryError,…
  • Và nhiều cách được cung cấp bởi arrow.core.Either.Companion.
suspend fun findUserByIdFromDb(id: String): UserDb? = TODO()

fun UserDb.toUser(): User = TODO()

fun Throwable.toUserException(): UserException = TODO()

suspend fun findUserById(id: UserId): Either<UserException, User?> =
    Either
        .catch { findUserByIdFromDb(id.value)?.toUser() } // Either<Throwable, User?>
        .mapLeft { it.toUserException() }                 // Either<UserException, User?>

Chúng ta có thể kiểm tra Either là giá trị Left hay Right, thông qua hai function là isLeft()isLeft(). Either cũng cung cấp hai function tap (tương tự onSucesscủa Result) và tapLeft (tương tự onFailure của Result).

val result: Either<UserException, User?> = findUserById(UserId("#id"))
result.isLeft()
result.isRight()
result.tap { u: User? -> println(u) }
result.tapLeft { e: UserException -> println(e) }

Tương tự như Result, chúng ta sử dụng các function getOrElse, orNull, getOrHandle để lấy giá trị mà Right chứa nếu nó là Right. Một số function hữu ích nữa là fold, bimap, mapError, filter,…

val result: Either<UserException, User?> = findUserById(UserId("#id"))

// Access value
result.getOrElse { defaultValue }
result.orNull()
result.getOrHandle { e: UserException -> defaultValue(e) }

fun handleUser(u: User?) {}
fun handleError(e: UserException) {
    // handle UserException
}

result.fold(
    ifRight = { handleUser(it) },
    ifLeft = { handleError(it) }
)

Tương tự ví dụ khi sử dụng Result, chúng ta cũng muốn chain nhiều giá trị Either với nhau

// (UserId) -> Either<UserException, User?>
suspend fun findUserById(id: UserId): Either<UserException, User?> = TODO()

// User -> Either<UserException, List<Post>>
suspend fun getPostsByUser(user: User): Either<UserException, List<Post>> = TODO()

// List<Post> -> Either<UserException, Unit>
suspend fun doSomethingWithPosts(posts: List<Post>): Either<UserException, Unit> = TODO()

Thư viện Arrow-kt đã cung cấp sẵn function flatMap và block either { ... } để có thể chain các Either với nhau dễ dàng. Trong either { ... } block, sử dụng function bind() để lấy giá trị R từ Either<L, R>. Nếu bind được gọi trên một Either chứa giá trị Left, thì phần code ở phía dưới nó trong block either { ... } sẽ bị bỏ qua (cơ chế short-circuits).

import arrow.core.*

class UserNotFoundException() : UserException("User is null", null)

val result: Either<UserException, Unit> = findUserById(UserId("#id"))
    .flatMap { user: User? ->
        if (user == null) UserNotFoundException().left()
        else user.right()
    }
    .flatMap { getPostsByUser(it) }
    .flatMap { doSomethingWithPosts(it) }

// or either block

val result: Either<UserException, Unit> = either { /*this: EitherEffect*/
    val userNullable: User? = findUserById(UserId("#id")).bind()
    val user: User = ensureNotNull(userNullable) { UserNotFoundException() }
    val posts: List<Post> = getPostsByUser(user).bind()
    doSomethingWithPosts(posts).bind()
}

Cuối cùng là cách khôi phục lỗi. Tương tự như recoverrecoverCatching của Result, chúng ta có thể sử dụng hai function handleErrorhandleErrorWith (giống như flatMap nhưng theo nhánh Left).

class MyData(...)

suspend fun getFromRemote(): MyData = TODO()
suspend fun getFromCache(): MyData = TODO()

val result: Either<Throwable, MyData> =
    Either
        .catch { getFromRemote() }
        .handleErrorWith { e: Throwable ->
            Either.catch {
                logger.error(e, "getFromRemote")
                getFromCache()
            }
        }

Kết luận

Chúng ta đã cùng tìm hiểu Result và sau đó là Either, cả hai type giúp xử lý lỗi và làm giảm side effect. Either còn chỉ rõ về những lỗi có thể xảy ra mà chỉ cần nhìn vào signature của một function. Ngoài ra, Either hỗ trợ cho suspend function mà không làm mất đi cơ chế cancellation, và Arrow-kt cũng có module Fx (https://arrow-kt.io/docs/fx/) giúp cho việc sử dụng Kotlin Coroutines dễ dàng hơn, khi viết các chương trình asyncconcurrent.

Hy vọng bạn thích bài viết này và hôm nay bạn đã học được điều gì đó hữu ích!

Tài liệu tham khảo

  • Arrow-kt – Either docs
  • Arrow-kt – Error handlding
  • Arrow-kt – Monad comprehension
  • Ciocîrlan, D. (2021) Idiomatic error handling in scala, Rock the JVM Blog. Available at: https://blog.rockthejvm.com/idiomatic-error-handling-in-scala/ (Accessed: 04 October 2024).

Author: st-hocnguyen

Related Blog

Our culture

+0

    From Seeking The Path to Leading The Way: Phuoc’s Journey at SupremeTech

    Are you curious how someone with no IT background made a bold leap into tech and ended up leading a team? Starting with no formal IT background, Phuoc took a leap of faith into the world of Infrastructure at SupremeTech. What began as a fresh start during the pandemic has become an inspiring tech career journey from entry-level newcomer to the leader of our Infrastructure team. In this inspiring interview, Phuoc shares the lessons learned, the power of making mistakes, and how embracing challenges helped shape his career in tech. First Impressions That Last Hi Phuoc! What was your first impression when you joined SupremeTech?I still remember my first day at SupremeTech. What impressed me most… was the smell of a brand-new office! (laughs)It might sound funny, but that paint smell felt comforting. It reminded me of my first job after graduation, working at a new construction site—filled with excitement, hope, and anticipation. Whenever I catch that same scent, it brings back the feeling of a fresh start. From Tourism to Tech: A Career Switch Sparked by Fate We heard you used to work in the tourism industry. What made you switch to IT?Yes, I worked as an admin in the tourism sector. Shifting careers felt like fate. Honestly, it might sound silly, but I chose SupremeTech mainly because they offered a MacBook! (laughs).At the time, I was looking to change my career to IT Infrastructure and had passed interviews at two companies. But when I discovered SupremeTech would provide a MacBook, I was so excited I couldn’t say no.Back then, I felt like a blank sheet of paper. Starting in a completely new field was a huge challenge. But thanks to the support from my teammates, I slowly adapted and began to grow. Starting During COVID: Remote Work and Early Struggles Changing industries isn’t easy. What was the toughest challenge for you?I joined SupremeTech during the COVID pandemic, so the biggest challenge was starting remotely. I didn’t know anyone, and everything was done over Google Meet. Building connections, understanding the work, or communicating effectively was hard. When we finally returned to the office, I was so happy to meet my teammates, mentors, and colleagues in person. That’s when my real learning journey began.One of the most memorable challenges? Making mistakes. I’ve never been afraid of being wrong—in fact, I enjoy it. I made many mistakes initially, but each one taught me something. Most of them happened because I didn’t think far enough ahead. Over time, I learned to be more thoughtful and less overconfident. Lessons from Mistakes: Learning the Hard Way How did you manage to get through those mistakes?Mistakes are valuable lessons. Now, I even create small “traps” in internship assignments based on the mistakes I once made. It helps them encounter real problems and learn through hands-on experience. You remember things better when you figure them out yourself, rather than just reading about them. After every project, our team writes a retrospective report noting what could have been done better. One mistake equals one lifelong lesson. Facing Challenges with a Grateful Mindset You talk a lot about challenges—what does that word mean to you?To me, challenges are a kind of “fate”. They don’t just happen by chance. You have to find a way to overcome them when they show up.They might feel overwhelming at the moment, but when I look back, I feel grateful—even thankful for the people who gave me those challenges. Every company has its problems. What matters is how you deal with them and what you learn along the way. From Fresher to Team Leader: A Role Earned Through Action You’re a team leader now. How did that role come to you?Honestly, I didn’t expect to become a leader so soon. But I’ve never been the type to wait around for task assignment. At the associate level, I tried to help interns and share my experience. I focused on building strong communication and genuine connections.As a mentor, I always try to lead by example. So when I was promoted, I already felt ready. When you sincerely help others, good things naturally come your way. A Culture of Calm and Growth What’s something special about the work environment at SupremeTech?SupremeTech has a very peaceful work environment. There’s no office politics or unnecessary drama. It’s a safe and supportive place where people can grow. But that doesn’t mean the work is easy. During projects, it can feel like going into battle. Everyone has to stay sharp and take ownership to solve problems. It’s an outstanding balance—our culture is kind, but our work ethic is fierce. That reflects SupremeTech's core values: be kind in life and embrace Passion and Challenge at work. Words of Advice for Young IT Professionals What would you say to young people just starting their careers in IT?Make mistakes while you still can. Don’t be afraid to be wrong. You’ll learn more from your errors than from any books.Don’t be afraid to try. Don’t avoid difficult things, especially if you want to grow beyond your comfort zone. Looking Back: Any Regrets? Looking back at your tech career journey, do you have any regrets?Not at all. Every step I’ve taken has been worth it. Skills are essential, but the environment shapes who you become. I love investigating new problems and finding solutions. My curiosity has given me more experiences than most people at my level haven’t had, which helps me grow every day. Final thought Thank you, Phuoc, for sharing your honest and inspiring story. We wish you continued passion, positivity, and success on your tech career journey with SupremeTech!

    11/04/2025

    63

    Our culture

    +0

      From Seeking The Path to Leading The Way: Phuoc’s Journey at SupremeTech

      11/04/2025

      63

      Our success stories

      +0

        How to Upgrade Aurora MySQL Databases: Lessons Learned from SupremeTech

        Upgrading a critical database like Aurora MySQL can feel daunting. We want better performance and a smooth system, but downtime and data risks can loom large. At SupremeTech, we’ve tackled this challenge head-on and shared our proven approach.  This insight comes from Mr. Phuoc Pham, our Infrastructure Manager, who presented at the morning session of "Harnessing AI on AWS: Transforming Software Builders for the Future" event by AWS and MegazoneCloud. The event focused on giving software companies tools, strategies, and real-world solutions to innovate, boost performance, and grow globally with AI. In his talk, Mr. Phuoc revealed our 6-step process that minimizes risks, protects data, and increases efficiency. Here’s how we did it, key lessons learned, and how you can ensure a smooth and risk-free database upgrade. Mr. Phuoc Pham, our Infrastructure Manager, presented the lesson learned from Aurora MySQL upgrades SupremeTech’s contribution to the AWS and Megazone event SupremeTech partners with AWS and MegazoneCloud to share our expertise in tackling technical challenges. In the morning session, Mr. Phuoc Pham delivered a presentation on lessons learned from Aurora MySQL upgrades, offering practical tips for software companies to optimize their infrastructure. In the afternoon, our chairman, Mr. Truong Dinh Hoang, joined a panel discussion on future trends for ISVs, highlighting strategies for growth and innovation. These contributions underscored SupremeTech’s commitment to helping businesses enhance performance and scale smarter. In the afternoon panel discussion, Mr. Truong Dinh Hoang shared about the market expansion and future trends for ISVs. The Challenges of Upgrading Aurora MySQL Mr. Phuoc kicked off by sharing real-world challenges we faced with a client’s Aurora MySQL upgrades: Minimal downtime: We had to finish in under 2 hours, including rollback time if needed.System stability: Our database powers multiple services, so it had to stay reliable post-upgrade.Fast rollback: We needed a quick way to revert without losing data if something went wrong.User impact: Our process had to keep disruptions low and customer trust high. These hurdles might sound familiar if you’ve upgraded a system. The key to achieving this is a structured and well-tested upgrade process. Mr. Phuoc Pham presented the challenges of upgrades for our client’s system. The 6-Step Database Upgrade Process At SupremeTech, we follow a 6-step upgrade process to ensure a smooth transition. Step 1: Collect and Analyze Data Before the Upgrade Preparation is everything. Before making any changes, assessing your current database setup is essential. This helps identify potential risks and prepare for a smooth transition. Mr. Phuoc emphasized checking: Database Schema & Objects – Make sure there are no conflicts with the new version.Connected Applications – Identify all services using the database.Custom Database Settings – Compare parameter changes between versions.Performance Metrics – Monitor CPU, memory, query latency, and transaction speed. We gather this information using tools like database logs, security groups, and queries like SHOW FULL PROCESSLIST. This step prepares us for a smooth upgrade. Mr. Phuoc shared one of our 6-step upgrade processes. Step 2: Choose the Right Upgrade Method with C.I.D.D.E.R Framework Not all upgrade methods are the same. Depending on your system’s needs, you may choose one of the following: Snapshot Restore – Reliable but requires full backup and longer downtime.Clone Cluster – Fast rollback but requires additional storage.In-Place Upgrade – Minimal downtime but higher risk.Blue/Green Deployment – Safest rollback option but costly. At SupremeTech, we use the C.I.D.D.E.R framework to decide the best method based on: Complexity: How hard is the upgrade?Infrastructure Cost: What’s the budget hit?Downtime: How long will it take?Dependencies: What else relies on our database?Expertise: Do we have the skills?Rollback Strategy: How easy is it to undo? Choosing the right upgrade method can reduce risk and save time. For this case—a 10GB database, multiple services, and a team still building experience—we chose an in-place upgrade with a clone cluster backup for quick rollback by renaming the database cluster. It kept the endpoint intact and downtime under 2 hours. Step 3: Test with a Dry Run “There’s no place like production,” Mr. Phuoc quipped, stressing the need for practice.  A dry-run is a test upgrade performed in a staging environment to catch problems before they affect real users. We run dry runs on a cloned database and DEV/STG environments to: Detects issues before they impact production.Reduces unexpected downtime.Helps estimate the actual upgrade time. This extra step can save hours of troubleshooting later. Step 4: Fine-Tuning Based on Dry-Run Results After testing, we adjust the process: Adjust database settings.Fix errors from the dry run.Shorten execution time for less downtime.Refine rollback procedures.Update guides for our team. A few small tweaks before the upgrade can prevent major issues after it. Step 5: Deployment – The Actual Upgrade With everything tested and fine-tuned, it's time to execute the upgrade in production. How we ensure success: Perform the upgrade during low-traffic hours.Keep the rollback plan ready.Monitor logs in real time for any errors. Having a clear step-by-step deployment plan prevents last-minute surprises. Step 6: Monitor After the Upgrade Post-upgrade, we track key metrics like: Resources: CPU, memory, disk usage.Performance: Query response time, QPS, TPS.Errors: Any glitches or slow queries.Data Integrity: No data loss or corruption. Continuous monitoring after the upgrade helps us spot issues quickly, reducing troubleshooting time and minimizing the impact on our customers. We monitor key performance metrics for both the new and old databases to compare. We also watch the four golden signals—latency, traffic, errors, and saturation—to get a full picture of system health. At SupremeTech, we use AI-powered tools like Amazon Q to analyze database logs and detect anomalies faster than manual monitoring. Why post-upgrade monitoring matters: Quickly identifies hidden performance issues.Ensures the upgrade was 100% successful.Helps optimize for better database efficiency. Boosted performance and customer trust are critical criteria when we implement upgrades. Results & Lessons Learned Our Results By following this 6-step process, SupremeTech successfully upgraded Aurora MySQL with: Done in under 2 hours of downtime.Lowered infra costs with smarter planning.Boosted performance and customer trust. Key Takeaways Mr. Phuoc wrapped up with these gems: Prep is everything: Gathering and analyzing info before the upgrade is critical to spot risks early.Plan for data checks: We ensure data integrity with a solid verification plan.Pick the right approach: We choose deployment and rollback methods that fit our clients’ operations.Keep monitoring: Continuous tracking helps us stay ahead of issues.Automate with AI: Using AI and tools speeds us up and cuts errors. Wrapping Up Upgrading a database doesn’t have to be a risky, stressful process. You can confidently upgrade with the right preparation, testing, and monitoring. Thanks to Mr. Phuoc Pham’s presentation at the AWS and MegazoneCloud event, our 6-step process at SupremeTech proves you can keep risks low, protect data, and emerge stronger when doing Aurora MySQL upgrades. If your company is planning a database upgrade and needs expert guidance, contact our team at SupremeTech. We help businesses upgrade critical databases without disruption. Want to learn more about cloud database best practices? Stay tuned for more insights from our tech experts! Related articles about AWS: Mastering AWS Lambda: An Introduction to Serverless ComputingCreate Your First AWS Lambda Function (Node.js, Python, and Go)Triggers and Events: How AWS Lambda Connects with the WorldBest Practices for Building Reliable AWS Lambda Functions

        21/03/2025

        133

        Our success stories

        +0

          How to Upgrade Aurora MySQL Databases: Lessons Learned from SupremeTech

          21/03/2025

          133

          Our success stories

          +0

            SupremeTech Partners with AWS and MegazoneCloud to Drive AI-Powered Business Growth

            SupremeTech is pleased to announce our collaboration with AWS and MegazoneCloud for an upcoming event, Harnessing AI on AWS: Transforming Software Builders for the Future, scheduled for March 20, 2025, in Da Nang. This event is about giving software companies the tools, strategies, and real-world solutions they need to spark innovation, boost performance, and even take their businesses global with AI. The software world is changing fast, and Artificial Intelligence is leading the charge. Companies that tap into AI on AWS are finding new ways to grow, streamline their workflows, and stay ahead of the game. This event offers software firms in Da Nang and beyond the chance to see how AI can level up your business and prepare them for the future. SupremeTech’s Contribution to the Event In partnership with AWS and MegazoneCloud, SupremeTech will share valuable insights from our experience mastering complex technical challenges, such as Aurora MySQL upgrades. We will break it down into practical tips and solutions that software companies can use to fine-tune their infrastructure and grow smarter. The SupremeTech partners with AWS and MegazoneCloud event is structured into two key sessions: Morning Session: Accelerating Technical Performance Enhancing Product Value with AI/ML Services: Attendees will learn how AWS’s advanced tools, including Amazon SageMaker and Bedrock, can optimize infrastructure, improve performance, and reduce time to market.Real-World Solutions: Megazone will present hands-on demonstrations of AI services on AWS, offering insights into seamless integration and proven strategies derived from their own expertise. Afternoon Session: Strategic Growth Expansion Scaling with AWS Programs: Discover how AWS initiatives such as the ISV Accelerate and Workload Migration Program (WMP) can accelerate market expansion and support rapid business growth.Global Opportunities with MegazoneCloud: Explore how MegazoneCloud’s extensive partner network and the AWS ecosystem can help software companies bring their products to international markets. This event is more than a technical gathering; it represents a strategic opportunity for software businesses to advance their capabilities and adopt AI effectively on AWS. Why You Should Attend Actionable Strategies: Gain practical knowledge to integrate AI into your business operations.Expert Insights: Benefit from the expertise of SupremeTech, AWS, and MegazoneCloud leaders with proven success in the AI landscape.Networking: Connect with industry peers and potential partners within Da Nang’s growing tech community.Global Expansion: Access tools and programs to scale your business internationally. Event Details Date: March 20, 2025Location: Voco Ma Belle Danang - 168 Vo Nguyen Giap Street, Son Tra Da Nang, Vietnam Register Today to Stay Ahead in the AI Era Do not miss this opportunity to leverage AI on AWS and position your software business for success. Join the event that SupremeTech partners with AWS and MegazoneCloud on March 20, 2025, to grab the insights and tools you need to lead the charge in innovation and growth. Click Here to Register Now and take the first step toward a future of innovation and growth. Related articles about AWS: Mastering AWS Lambda: An Introduction to Serverless ComputingCreate Your First AWS Lambda Function (Node.js, Python, and Go)Triggers and Events: How AWS Lambda Connects with the WorldBest Practices for Building Reliable AWS Lambda Functions

            11/03/2025

            173

            Ngan Phan

            Our success stories

            +0

              SupremeTech Partners with AWS and MegazoneCloud to Drive AI-Powered Business Growth

              11/03/2025

              173

              Ngan Phan

              E-commerce (Shopify)

              +0

                How to Build a High-Performing E-commerce Store

                E-commerce is growing every year and is set to make heavy profits, with more and more people opting for it. However, with ever-growing competition in this domain, you need to stand out to stay afloat. You have to compete with giants like Amazon, eBay, and Alibaba, which can give you a tough time. In this blog, we will discuss building a high-performing e-commerce store in detail. So, let’s get started. See more: Exploring 7 Top Online Food Ordering Systems for Small BusinessesSmooth Sailing: How to Migrate Website to Shopify? Step-by-Step Procedure for Building an E-commerce Store E-commerce stores are becoming increasingly popular due to their range of products on a single platform, short delivery time, and easy payment options. Let’s go through a step-by-step procedure for building an attractive and high-performing e-commerce store. Step 1: Choose Your Platform Each e-commerce store is unique and has its own goals and target audience. Hence, you need to choose an ideal e-commerce platform for your needs. There are a number of options available including Shopify, WooCommerce, Squarespace, WordPress and more.  These eCommerce platforms have their own features, so you should discuss each one with your development team and pick the most suitable one for your needs. Step 2: Create an Account on the Chosen Platform Once you have chosen your eCommerce store platform, you need to purchase the subscription, in case it is not open source. These platforms offer a variety of plans, uptime guarantees, and security features.  If you have chosen an all-in-one e-commerce platform, all you need to do is go to the provider’s website and create an account. Then, you select a plan and pay for it if it is not free. Step 3: Choose a Template After you have decided on your eCommerce platform, you will have a variety of options regarding templates. Each has its own colors, fonts, and layouts, which gives an e-commerce store a consistent look and feel. Templates can be free or premium ones, for which you need to pay. Generally speaking, paid ones offer more features and designs. This saves time which will be spent on coming up with designs from scratch. Step 4: Build Your Webpages & Product Pages You must not use the template as it is; you should customize it according to your requirements. Some common customizations include adding your logo and contact details.  Other changes could be adding product images, configuring your site navigation, and building check-out and returns pages. Step 5: Write Product Descriptions As it is not a brick-and-mortar store where customers can view the products or feel them, you need to work on your product descriptions along with images. They need to be very accurate, easy to understand, and detailed. It should include basic details, along with information about who the product is meant for and where it can be used.  Product images should be high-definition and of the same size, and should show the product from all possible angles.  Step 6: Set Up Payment Gateway As most of your customers will opt for online payments and not Cash on Delivery, you need to have a secure payment gateway. So, integrate secure payment options on your e-Commerce store, which are hassle-free, fast and secure at the same time.  If you redirect your customers to other platforms like PayPal, ensure that data is fully encrypted.  If your payment options are not convenient, no matter how good your product catalog is, customers will not come back. Step 7: Integrate Shipping  The platform you have chosen for your e-Commerce store may allow integrated shipping along with selling. This creates a seamless customer experience and lets you focus on selling products.  You also need to decide on your shipping policy, such as free shipping, flat rates, variable fees, etc. Along with this, you need to decide on your returns and refund policy to make the situation clear for your customers. Step 8: Test & Launch Your e-Commerce Store After all the hard work, it is time to test your e-commerce store before launching it. You should do rigorous testing to ensure there are no bottlenecks and pain points. You can do the testing in-house or outsource the task.  Check all links, buttons, and navigation options and ensure they work. Payment processing should also be thoroughly checked. Your e-commerce store should be compatible with desktop, mobile devices, and all browsers. Once everything has been checked, you are ready for launch. Popular eCommerce Platforms To Consider Several options are available for e-commerce platforms. Let’s discuss some popular ones to help you choose. Shopify Shopify is an eCommerce platform suitable for Web, iOS, and Android. It is easy to set up and has all the necessary tools. The support and resources provided are best in class, which makes it popular and effective.  The only constraint of Shopify is that it can be expensive if you add many extra apps. Many eCommerce stores currently run on Shopify, which has been around for 18 years and is ideal for small businesses that want to go online. BigCommerce BigCommerce is an e-commerce platform suitable for Web, iOS, and Android devices. It is the SMB version of a very popular enterprise eCommerce platform. It has integrated features like shipping and taxes to encourage established businesses online. However, it is not recommended for small retailers setting up their businesses.   It also enables listing your products on e-commerce giants like eBay, Walmart, and Amazon.  As a result, customers do not necessarily have to buy from your store.   BigCommerce has 12 free themes, all of which have a great look. They also have a drag-and-drop site builder that can be used to customize the look.  WooCommerce   WooCommerce is an e-commerce platform for the Web, iOS, and Android. It provides all the flexibility of WordPress, is widely supported, and has many apps and integrations. Installing WooCommerce on your website is very easy, similar to installing any  other plugin on WordPress. If you use WordPress for your eCommerce store, you should ideally go for WooCommerce. Wrapping Up E-commerce is still nascent and will continue to grow over the decade. It provides a range of products and the convenience of buying them from your home from across the world. So, whether you are starting or have an established business, you should consider going online, as it will increase your reach. After considering everything, you should choose your e-commerce store platform. This will ensure that you have a high-performing e-commerce store. For building your e-Commerce store, get in touch with SupremeTech. 

                10/03/2025

                102

                E-commerce (Shopify)

                +0

                  How to Build a High-Performing E-commerce Store

                  10/03/2025

                  102

                  Customize software background

                  Want to customize a software for your business?

                  Meet with us! Schedule a meeting with us!