Database/MS-SQL

[스크랩] SQL Server 트랜잭션 로그 아키텍처 및 관리 가이드

99iberty 2018. 7. 8. 21:01


https://docs.microsoft.com/ko-kr/sql/relational-databases/sql-server-transaction-log-architecture-and-management-guide?view=sql-server-2017


SQL Server 트랜잭션 로그 아키텍처 및 관리 가이드SQL Server Transaction Log Architecture and Management Guide


이 항목 적용 대상: 예SQL Server예Azure SQL 데이터베이스예Azure SQL 데이터 웨어하우스 예 병렬 데이터 웨어하우스THIS TOPIC APPLIES TO: yesSQL ServeryesAzure SQL DatabaseyesAzure SQL Data Warehouse yesParallel Data Warehouse

SQL ServerSQL Server 데이터베이스에는 각 트랜잭션에 의해 적용된 모든 트랜잭션 및 데이터베이스 수정 내용을 기록하는 트랜잭션 로그가 있습니다.Every SQL ServerSQL Server database has a transaction log that records all transactions and the database modifications that are made by each transaction. 트랜잭션 로그는 데이터베이스의 주요 구성 요소이며 시스템 오류가 발생할 경우 데이터베이스를 다시 일관된 상태로 만들려면 트랜잭션 로그가 필요할 수 있습니다.The transaction log is a critical component of the database and, if there is a system failure, the transaction log might be required to bring your database back to a consistent state. 이 지침에서는 트랜잭션 로그의 물리적 및 논리적 아키텍처에 대한 정보를 제공합니다.This guide provides information about the physical and logical architecture of the transaction log. 아키텍처를 이해하면 트랜잭션 로그를 보다 효율적으로 관리할 수 있습니다.Understanding the architecture can improve your effectiveness in managing transaction logs.

트랜잭션 로그 논리 아키텍처Transaction Log Logical Architecture

SQL ServerSQL Server 트랜잭션 로그는 로그 레코드 문자열처럼 논리적으로 작동합니다.The SQL ServerSQL Server transaction log operates logically as if the transaction log is a string of log records. 각 로그 레코드는 LSN(로그 시퀀스 번호)으로 식별됩니다.Each log record is identified by a log sequence number (LSN). 각 새 로그 레코드는 LSN과 함께 로그의 논리적 끝에 작성되며 이때 LSN은 오름차순입니다.Each new log record is written to the logical end of the log with an LSN that is higher than the LSN of the record before it. 로그 레코드는 작성된 순서대로 저장됩니다.Log records are stored in a serial sequence as they are created. 각 로그 레코드에는 자신이 속한 트랜잭션의 ID가 포함됩니다.Each log record contains the ID of the transaction that it belongs to. 각 트랜잭션에서 트랜잭션과 관련된 모든 로그 레코드는 트랜잭션의 롤백 속도를 높이는 후방 포인터로 체인에 개별적으로 연결되어 있습니다.For each transaction, all log records associated with the transaction are individually linked in a chain using backward pointers that speed the rollback of the transaction.

데이터 수정에 대한 로그 레코드는 수행된 논리적 연산이나 수정된 데이터의 이전 이미지와 이후 이미지를 기록합니다.Log records for data modifications record either the logical operation performed or they record the before and after images of the modified data. 이전 이미지는 연산이 수행되기 전의 데이터 복사본이고 이후 이미지는 연산이 수행된 후의 데이터 복사본입니다.The before image is a copy of the data before the operation is performed; the after image is a copy of the data after the operation has been performed.

연산을 복구하는 단계는 다음과 같이 로그 레코드의 유형에 따라 다릅니다.The steps to recover an operation depend on the type of log record:

  • 기록된 논리적 연산Logical operation logged

    • 논리적 연산을 롤포워드하기 위해 해당 연산이 다시 수행됩니다.To roll the logical operation forward, the operation is performed again.

    • 논리적 연산을 롤백하기 위해 역 논리적 연산이 수행됩니다.To roll the logical operation back, the reverse logical operation is performed.

  • 기록된 이전 및 이후 이미지Before and after image logged

    • 연산을 롤포워드하기 위해 이후 이미지가 적용됩니다.To roll the operation forward, the after image is applied.

    • 연산을 롤백하기 위해 이전 이미지가 적용됩니다.To roll the operation back, the before image is applied.

많은 유형의 작업이 트랜잭션 로그에 기록됩니다.Many types of operations are recorded in the transaction log. 다음과 같은 작업이 여기에 포함됩니다.These operations include:

  • 각 트랜잭션의 시작과 끝The start and end of each transaction.

  • 모든 데이터 수정 내용(삽입, 업데이트 또는 삭제).Every data modification (insert, update, or delete). 여기에는 시스템 테이블을 비롯하여 모든 테이블에 대해 시스템 저장 프로시저 또는 DDL(데이터 정의 언어) 문에서 수행한 변경 내용이 포함됩니다.This includes changes by system stored procedures or data definition language (DDL) statements to any table, including system tables.

  • 모든 익스텐트 및 페이지 할당 또는 할당 취소Every extent and page allocation or deallocation.

  • 테이블이나 인덱스 만들기 또는 삭제Creating or dropping a table or index.

    롤백 작업도 기록됩니다.Rollback operations are also logged. 각 트랜잭션은 트랜잭션 로그에 공간을 예약하여 명시적 롤백 문이나 오류로 인해 발생한 롤백을 지원하기에 충분한 로그 공간을 확보합니다.Each transaction reserves space on the transaction log to make sure that enough log space exists to support a rollback that is caused by either an explicit rollback statement or if an error is encountered. 예약된 공간의 크기는 트랜잭션에서 수행되는 작업에 따라 다르지만 일반적으로 각 작업을 기록하는 데 사용되는 공간의 크기와 같습니다.The amount of space reserved depends on the operations performed in the transaction, but generally it is equal to the amount of space used to log each operation. 이렇게 예약된 공간은 트랜잭션 완료 시 해제됩니다.This reserved space is freed when the transaction is completed.

마지막으로 작성된 로그 레코드로의 성공적인 데이터베이스 차원의 롤백에 필요한 첫 번째 로그 레코드의 로그 파일 섹션을 로그의 활성 부분 또는 활성 로그라고 합니다.The section of the log file from the first log record that must be present for a successful database-wide rollback to the last-written log record is called the active part of the log, or the active log. 로그의 이 섹션은 데이터베이스의 전체 복구를 수행하는 데 필요합니다.This is the section of the log required to a full recovery of the database. 활성 로그는 어떤 부분도 잘라낼 수 없습니다.No part of the active log can ever be truncated. 이 첫 번째 로그 레코드의 LSN(로그 시퀀스 번호)최소 복구 LSN( MinLSN)이라고 합니다.The log sequence number (LSN) of this first log record is known as the minimum recovery LSN (MinLSN).

트랜잭션 로그 물리 아키텍처Transaction Log Physical Architecture

데이터베이스의 트랜잭션 로그는 하나 이상의 물리 파일에 매핑됩니다.The transaction log in a database maps over one or more physical files. 개념상으로 로그 파일은 로그 레코드의 문자열입니다.Conceptually, the log file is a string of log records. 실제로 로그 레코드의 시퀀스는 트랜잭션 로그를 구현하는 물리적 파일 집합에 효율적으로 저장됩니다.Physically, the sequence of log records is stored efficiently in the set of physical files that implement the transaction log. 데이터베이스마다 최소한 하나의 로그 파일이 있어야 합니다.There must be at least one log file for each database.

SQL Server 데이터베이스 엔진SQL Server Database Engine은 내부적으로 각 물리적 로그 파일을 여러 개의 VLF(가상 로그 파일)로 나눕니다.The SQL Server 데이터베이스 엔진SQL Server Database Engine divides each physical log file internally into a number of virtual log files (VLFs). 가상 로그 파일의 크기는 고정되어 있지 않으며 물리 로그 파일에 대해 고정된 수의 가상 로그 파일이 있는 것도 아닙니다.Virtual log files have no fixed size, and there is no fixed number of virtual log files for a physical log file. 데이터베이스 엔진Database Engine 은 로그 파일을 만들거나 확장할 때 동적으로 가상 로그 파일의 크기를 선택합니다.The 데이터베이스 엔진Database Engine chooses the size of the virtual log files dynamically while it is creating or extending log files. 데이터베이스 엔진Database Engine 은 적은 수의 가상 파일을 유지하려고 합니다.The 데이터베이스 엔진Database Engine tries to maintain a small number of virtual files. 로그 파일 확장 후 가상 파일 크기는 기존 로그 크기와 새 파일 증가 크기를 합한 크기입니다.The size of the virtual files after a log file has been extended is the sum of the size of the existing log and the size of the new file increment. 관리자가 가상 로그 파일의 크기 또는 수를 구성하거나 설정할 수 없습니다.The size or number of virtual log files cannot be configured or set by administrators.

참고

가상 로그 파일(VLF) 생성은 이 메서드를 따릅니다.Virtual log file (VLF) creation follows this method:

  • 다음 증가가 현재 로그의 물리적 크기의 1/8보다 작은 경우 증가 크기에 충분한 VLF를 하나 만듭니다( SQL Server 2014(12.x)SQL Server 2014 (12.x)로 시작).If the next growth is less than 1/8 of current log physical size, then create 1 VLF that covers the growth size (Starting with SQL Server 2014(12.x)SQL Server 2014 (12.x))
  • 다음 증가 현재 로그 크기의 1/8보다 많을 경우 pre-2014 메서드를 사용합니다.If the next growth is more than 1/8 of the current log size, then use the pre-2014 method:
    • 증가가 64MB보다 작은 경우 증가 크기에 충분한 4개의 VLF를 만듭니다(예: 1MB 증가의 경우 256KB VLF 4개 생성).If growth is less than 64MB, create 4 VLFs that cover the growth size (e.g. for 1 MB growth, create four 256KB VLFs)
    • 증가가 64MB에서 최대 1GB인 경우 증가 크기에 충분한 8개의 VLF를 만듭니다(예: 512MB 증가의 경우 64MB VLF 8개 생성).If growth is from 64MB up to 1GB, create 8 VLFs that cover the growth size (e.g. for 512MB growth, create eight 64MB VLFs)
    • 증가가 1GB보다 큰 경우 증가 크기에 충분한 16개의 VLF를 만듭니다(예: 8GB 증가의 경우 512MB VLF 16개 생성).If growth is larger than 1GB, create 16 VLFs that cover the growth size (e.g. for 8 GB growth, create sixteen 512MB VLFs)

수많은 작은 증가값에서 로그 파일이 크게 증가하는 경우 가상 로그 파일이 많이 생성됩니다.If the log files grow to a large size in many small increments, they will have many virtual log files. 이로 인해 데이터베이스 시작뿐 아니라 로그 백업 및 복원 작업이 느려질 수 있습니다.This can slow down database startup and also log backup and restore operations. 반대로 로그 파일이 적거나 하나의 증분인 큰 크기로 설정된 경우 적은 수의 매우 큰 가상 로그 파일이 포함됩니다.Conversely, if the log files are set to a large size with few or just one increment, they will have few very large virtual log files. 트랜잭션 로그의 필수 크기자동 증가 설정을 올바르게 예측하는 방법에 대한 자세한 내용은 트랜잭션 로그 파일의 크기 관리권장 사항 섹션을 참조하세요.For more information on properly estimating the required size and autogrow setting of a transaction log, refer to the Recommendations section of Manage the size of the transaction log file.

최적의 VLF 배포를 수행하기 위한 필수 증분을 사용하여 필요한 최종 크기에 가까운 크기 값을 로그 파일에 할당하고 growth_increment 값을 비교적 크게 지정하는 것이 좋습니다.We recommend that you assign log files a size value close to the final size required, using the required increments to achieve optimal VLF distribution, and also have a relatively large growth_increment value. 현재 트랜잭션 로그 크기에 대해 최적의 VLF 분포를 결정하려면 아래 팁을 참조하세요.See the tip below to determine the optimal VLF distribution for the current transaction log size.

  • ALTER DATABASESIZE 인수로 설정된 크기 값은 로그 파일의 초기 크기입니다.The size value, as set by the SIZE argument of ALTER DATABASE is the initial size for the log file.
  • growth_increment 값(자동 증가 값이라고도 함)은 ALTER DATABASEFILEGROWTH 인수로 설정된 대로 새로운 공간이 필요할 때마다 파일에 추가되는 공간입니다.The growth_increment value (also referred as the autogrow value), as set by the FILEGROWTH argument of ALTER DATABASE, is the amount of space added to the file every time new space is required.

ALTER DATABASEFILEGROWTHSIZE 인수에 대한 자세한 내용은 ALTER DATABASE(Transact-SQL) 파일 및 파일 그룹 옵션을 참조하세요.For more information on FILEGROWTH and SIZE arguments of ALTER DATABASE, see ALTER DATABASE (Transact-SQL) File and Filegroup Options.

주어진 인스턴스의 모든 데이터베이스의 현재 트랜잭션 로그 크기에 대한 최적의 VLF 분포 및 필수 크기를 수행할 필수 성장 증분을 결정하려면 이 스크립트를 참조하세요.To determine the optimal VLF distribution for the current transaction log size of all databases in a given instance, and the required growth increments to achieve the required size, see this script.

트랜잭션 로그는 순환 파일입니다.The transaction log is a wrap-around file. 예를 들어 데이터베이스에 4개의 VLF로 나뉜 물리 로그 파일이 한 개 있다고 가정합니다.For example, consider a database with one physical log file divided into four VLFs. 이 데이터베이스가 생성될 때 물리 로그 파일의 시작 부분에서 논리 로그 파일이 시작됩니다.When the database is created, the logical log file begins at the start of the physical log file. 새 로그 레코드는 논리 로그의 끝 부분에 추가되며 물리 로그의 끝 방향으로 확장됩니다.New log records are added at the end of the logical log and expand toward the end of the physical log. 로그 잘림을 수행하면 모든 레코드가 MinLSN(최소 복구 로그 시퀀스 번호) 앞에 있는 가상 로그에 대한 공간이 확보됩니다.Log truncation frees any virtual logs whose records all appear in front of the minimum recovery log sequence number (MinLSN). MinLSN 은 성공적인 데이터베이스 차원의 롤백에 필요한 가장 오래된 로그 레코드의 로그 시퀀스 번호입니다.The MinLSN is the log sequence number of the oldest log record that is required for a successful database-wide rollback. 예제 데이터베이스의 트랜잭션 로그는 다음 그림의 로그와 유사합니다.The transaction log in the example database would look similar to the one in the following illustration.

tranlog3

논리 로그의 끝 부분이 물리 로그 파일의 끝 부분에 도달하면 새 로그 레코드는 물리 로그 파일의 시작 부분으로 순환됩니다.When the end of the logical log reaches the end of the physical log file, the new log records wrap around to the start of the physical log file.

tranlog4

이러한 순환은 논리 로그 끝 부분이 논리 로그의 시작 부분에 도달하지 않는 한 계속 반복됩니다.This cycle repeats endlessly, as long as the end of the logical log never reaches the beginning of the logical log. 다음 검사점까지 생성되는 모든 새 로그 레코드를 위해 항상 충분한 공간이 남을 만큼 기존 로그 레코드가 자주 잘리면 로그는 가득 차지 않습니다.If the old log records are truncated frequently enough to always leave sufficient room for all the new log records created through the next checkpoint, the log never fills. 그러나 논리 로그의 끝 부분이 논리 로그의 시작 부분에 도달하면 다음 두 가지 상황 중 하나가 발생합니다.However, if the end of the logical log does reach the start of the logical log, one of two things occurs:

  • 로그에 대해 FILEGROWTH 설정이 사용하도록 설정되어 있고 디스크에 사용할 수 있는 공간이 있으면 파일은 growth_increment 매개 변수에 지정된 크기만큼 확장되며 새 로그 레코드가 확장 부분에 추가됩니다.If the FILEGROWTH setting is enabled for the log and space is available on the disk, the file is extended by the amount specified in the growth_increment parameter and the new log records are added to the extension. FILEGROWTH 설정에 대한 자세한 내용은 ALTER DATABASE 파일 및 파일 그룹 옵션(Transact-SQL)을 참조하세요.For more information about the FILEGROWTH setting, see ALTER DATABASE File and Filegroup Options (Transact-SQL).

  • FILEGROWTH 설정이 사용하도록 설정되어 있지 않거나 로그 파일이 있는 디스크의 사용 가능한 공간이 growth_increment에 지정된 크기보다 적으면 9002 오류가 발생합니다.If the FILEGROWTH setting is not enabled, or the disk that is holding the log file has less free space than the amount specified in growth_increment, an 9002 error is generated. 자세한 정보는 전체 트랜잭션 로그 문제 해결을 참조하세요.Refer to Troubleshoot a Full Transaction Log for more information.

    로그에 물리 로그 파일이 여러 개 있으면 논리 로그는 모든 물리 로그 파일을 거친 후 첫 번째 물리 로그 파일의 시작 부분으로 순환됩니다.If the log contains multiple physical log files, the logical log will move through all the physical log files before it wraps back to the start of the first physical log file.

중요

트랜잭션 로그 크기 관리에 대한 자세한 내용은 트랜잭션 로그 파일의 크기 관리를 참조하세요.For more information about transaction log size management, see Manage the Size of the Transaction Log File.

로그 잘림Log Truncation

로그가 가득 차지 않도록 하기 위해 로그 잘림은 필수적입니다.Log truncation is essential to keep the log from filling. 로그 잘림은 SQL ServerSQL Server 데이터베이스의 논리 트랜잭션 로그에서 비활성 가상 로그 파일을 삭제하여 물리적 트랜잭션 로그에서 다시 사용할 수 있도록 논리 로그의 공간을 확보합니다.Log truncation deletes inactive virtual log files from the logical transaction log of a SQL ServerSQL Server database, freeing space in the logical log for reuse by the physical transaction log. 트랜잭션 로그가 잘리지 않으면 물리적 로그 파일에 할당된 디스크 공간이 모두 트랜잭션 로그로 채워지게 됩니다.If a transaction log were never truncated, it would eventually fill all the disk space that is allocated to its physical log files. 단, 로그를 자르기 전에 검사점 작업을 수행해야 합니다.However, before the log can be truncated, a checkpoint operation must occur. 검사점은 현재 메모리 내의 수정된 페이지(더티 페이지라고 함)와 메모리의 트랜잭션 로그 정보를 디스크에 기록합니다.A checkpoint writes the current in-memory modified pages (known as dirty pages) and transaction log information from memory to disk. 검사점을 수행하면 트랜잭션 로그의 비활성 부분은 재사용 가능으로 표시됩니다.When the checkpoint is performed, the inactive portion of the transaction log is marked as reusable. 그런 후에는 로그 잘림으로 비활성 부분에 대한 공간을 확보할 수 있습니다.Thereafter, the inactive portion can be freed by log truncation. 검사점에 대한 자세한 내용은 데이터베이스 검사점(SQL Server)을 참조하세요.For more information about checkpoints, see Database Checkpoints (SQL Server).

다음 그림에서는 잘림 전과 후의 트랜잭션 로그를 보여 줍니다.The following illustrations show a transaction log before and after truncation. 첫 번째 그림은 잘림이 수행되지 않은 트랜잭션 로그를 보여 줍니다.The first illustration shows a transaction log that has never been truncated. 현재 논리 로그에서 4개의 가상 로그 파일을 사용하고 있습니다.Currently, four virtual log files are in use by the logical log. 논리 로그는 첫 번째 가상 로그 파일의 앞에서 시작하고 가상 로그 4에서 끝납니다.The logical log starts at the front of the first virtual log file and ends at virtual log 4. MinLSN 레코드는 가상 로그 3에 있습니다.The MinLSN record is in virtual log 3. 가상 로그 1과 가상 로그 2에는 비활성 로그 레코드만 포함되어 있습니다.Virtual log 1 and virtual log 2 contain only inactive log records. 이러한 레코드는 자를 수 있습니다.These records can be truncated. 가상 로그 5는 사용하지 않았으며 현재 논리 로그에 포함되지 않습니다.Virtual log 5 is still unused and is not part of the current logical log.

tranlog2

두 번째 그림은 잘림 후의 로그 모습을 보여 줍니다.The second illustration shows how the log appears after being truncated. 가상 로그 1과 가상 로그 2는 다시 사용할 수 있도록 공간이 확보되었습니다.Virtual log 1 and virtual log 2 have been freed for reuse. 이제 논리 로그는 가상 로그 3의 시작 부분에서 시작됩니다.The logical log now starts at the beginning of virtual log 3. 가상 로그 5는 아직 사용되지 않았으며 현재 논리 로그에 포함되지 않습니다.Virtual log 5 is still unused, and it is not part of the current logical log.

tranlog3

여타의 이유로 지연된 경우를 제외하고 로그 잘림은 다음과 같이 자동으로 발생합니다.Log truncation occurs automatically after the following events, except when delayed for some reason:

미리 쓰기 트랜잭션 로그Write-Ahead Transaction Log

이 섹션에서는 데이터 수정 내용을 디스크에 기록할 때 미리 쓰기 트랜잭션 로그의 역할에 대해 설명합니다.This section describes the role of the write-ahead transaction log in recording data modifications to disk. SQL ServerSQL Server에서는 WAL(미리 쓰기 로그)을 사용하여 연결된 로그 레코드가 디스크에 기록되기 전에는 어떠한 데이터 수정 내용도 디스크에 기록되지 않도록 합니다. uses a write-ahead logging (WAL) algorithm, which guarantees that no data modifications are written to disk before the associated log record is written to disk. 따라서 트랜잭션의 ACID 속성이 유지 관리됩니다.This maintains the ACID properties for a transaction.

미리 쓰기 로그 작동 방식을 이해하려면 수정된 데이터가 디스크에 기록되는 방법을 알아야 합니다.To understand how the write-ahead log works, it is important for you to know how modified data is written to disk. SQL ServerSQL Server 는 데이터를 검색해야 할 때 데이터 페이지를 읽어오는 버퍼 캐시를 유지 관리합니다. maintains a buffer cache into which it reads data pages when data must be retrieved. 페이지가 버퍼 캐시에서 수정될 때 페이지는 디스크에 바로 다시 기록되지 않고 대신 더티로 표시됩니다.When a page is modified in the buffer cache, it is not immediately written back to disk; instead, the page is marked as dirty. 데이터 페이지는 물리적으로 디스크에 기록되기 전에 두 개 이상의 논리적 쓰기를 수행할 수 있습니다.A data page can have more than one logical write made before it is physically written to disk. 각 논리적 쓰기의 경우 트랜잭션 로그 레코드는 수정 사항을 기록하는 로그 캐시에 삽입됩니다.For each logical write, a transaction log record is inserted in the log cache that records the modification. 로그 레코드는 관련된 더티 페이지가 버퍼 캐시에서 디스크로 제거되기 전에 디스크에 기록되어야 합니다.The log records must be written to disk before the associated dirty page is removed from the buffer cache and written to disk. 검사점 프로세스는 주기적으로 버퍼 캐시에서 지정된 특정 데이터베이스의 페이지를 포함하는 버퍼를 검색한 다음 모든 더티 페이지를 디스크에 기록합니다.The checkpoint process periodically scans the buffer cache for buffers with pages from a specified database and writes all dirty pages to disk. 검사점은 모든 더티 페이지가 디스크에 기록되었음을 확인하는 지점을 만들어 나중에 복구하는 동안 시간을 절약할 수 있습니다.Checkpoints save time during a later recovery by creating a point at which all dirty pages are guaranteed to have been written to disk.

버퍼 캐시에 있는 수정된 데이터 페이지를 디스크에 쓰는 작업을 페이지 플러시라고 합니다.Writing a modified data page from the buffer cache to disk is called flushing the page. SQL ServerSQL Server 에는 연결된 로그 레코드가 기록되기 전에 더티 페이지가 플러시되지 않도록 하는 논리가 있습니다. has logic that prevents a dirty page from being flushed before the associated log record is written. 로그 레코드는 로그 버퍼가 플러시되면 디스크에 기록됩니다.Log records are written to disk when the log buffers are flushed. 이는 트랜잭션이 커밋되거나 로그 버퍼가 가득 찰 때마다 발생합니다.This happens whenever a transaction commits or the log buffers become full.

트랜잭션 로그 백업Transaction Log Backups

이 섹션에서는 트랜잭션 로그를 백업 및 복원하거나 적용하는 방법에 대한 개념을 설명합니다.This section presents concepts about how to back up and restore (apply) transaction logs. 전체 및 대량 로그 복원 모델에서 데이터를 복구하려면 트랜잭션 로그를 정기적으로 백업(로그 백업)해야 합니다.Under the full and bulk-logged recovery models, taking routine backups of transaction logs (log backups) is necessary for recovering data. 전체 백업이 실행되는 동안 로그를 백업할 수 있습니다.You can back up the log while any full backup is running. 복구 모델에 대한 자세한 내용은 SQL Server 데이터베이스 백업 및 복원을 참조하세요.For more information about recovery models, see Back Up and Restore of SQL Server Databases.

첫 번째 로그 백업을 만들기 전에 데이터베이스 백업 또는 파일 백업 집합의 첫 번째 집합과 같은 전체 백업을 만들어야 합니다.Before you can create the first log backup, you must create a full backup, such as a database backup or the first in a set of file backups. 파일 백업만 사용하여 데이터베이스를 복원하면 복잡해질 수 있습니다.Restoring a database by using only file backups can become complex. 따라서 가능하면 처음에 전체 데이터베이스 백업을 수행하는 것이 좋습니다.Therefore, we recommend that you start with a full database backup when you can. 그런 후에 트랜잭션 로그를 정기적으로 백업할 수 있습니다.Thereafter, backing up the transaction log regularly is necessary. 이렇게 하면 작업 손실 위험이 최소화될 뿐만 아니라 트랜잭션 로그가 잘립니다.This not only minimizes work-loss exposure but also enables truncation of the transaction log. 일반적으로 기존 로그 백업 후에도 트랜잭션 로그가 잘리지만Typically, the transaction log is truncated after every conventional log backup.

중요

비즈니스 요구 사항, 특히 손상된 로그 저장소에 의해 발생될 수 있는 작업 손실에 대한 허용 범위를 지원하기 위해 로그 백업을 충분히 자주 수행하는 것이 좋습니다.We recommend taking frequent enough log backups to support your business requirements, specifically your tolerance for work loss such as might be caused by a damaged log storage. 로그 백업의 적절한 수행 빈도는 저장 및 관리는 물론 복원까지 가능할 수 있는 로그 백업의 횟수에 의해 조정되는 작업 손실 위험에 대한 허용 범위에 따라 달라집니다.The appropriate frequency for taking log backups depends on your tolerance for work-loss exposure balanced by how many log backups you can store, manage, and, potentially, restore. 복구 전략을 구현할 때 필요한 RTORPO, 특히 로그 백업 케이던스에 대해 생각해보세요.Think about the required RTO and RPO when implementing your recovery strategy, and specifically the log backup cadence. 로그 백업에 걸리는 시간은 매 15분에서 30분이면 충분합니다.Taking a log backup every 15 to 30 minutes might be enough. 비즈니스에서 작업 손실 위험을 최소화하려는 경우에는 로그 백업을 더 자주 수행해야 합니다.If your business requires that you minimize work-loss exposure, consider taking log backups more frequently. 로그 백업 횟수가 많아지면 로그 잘림이 더 자주 발생하여 로그 파일의 크기가 작아지는 이점이 있습니다.More frequent log backups have the added advantage of increasing the frequency of log truncation, resulting in smaller log files.

중요

복원해야 하는 로그 백업의 수를 제한하려면 데이터를 정기적으로 백업해야 합니다.To limit the number of log backups that you need to restore, it is essential to routinely back up your data. 예를 들어 주별 전체 데이터베이스 백업과 일별 차등 데이터베이스 백업을 예약할 수 있습니다.For example, you might schedule a weekly full database backup and daily differential database backups.
또 복구 전략을 구현할 때 필요한 RTORPO, 특히 전체 및 차등 데이터베이스 백업 케이던스에 대해 생각해보세요.Again, think about the required RTO and RPO when implementing your recovery strategy, and specifically the full and differential database backup cadence.

트랜잭션 로그 백업에 대한 자세한 내용은 트랜잭션 로그 백업(SQL Server)을 참조하세요.For more information about transaction log backups, see Transaction Log Backups (SQL Server).

로그 체인The Log Chain

로그 백업의 연속 시퀀스를 로그 체인이라고 합니다.A continuous sequence of log backups is called a log chain. 로그 체인은 데이터베이스의 전체 백업으로 시작합니다.A log chain starts with a full backup of the database. 일반적으로 데이터베이스를 처음 백업할 때나 단순 복구 모델에서 전체 또는 대량 로그 복구 모델로 전환한 후에만 새 로그 체인이 시작됩니다.Usually, a new log chain is only started when the database is backed up for the first time or after the recovery model is switched from simple recovery to full or bulk-logged recovery. 전체 데이터베이스 백업을 만들 때 기존 백업 집합을 덮어쓰도록 선택하지 않으면 기존 로그 체인이 그대로 유지됩니다.Unless you choose to overwrite existing backup sets when creating a full database backup, the existing log chain remains intact. 로그 체인이 그대로 유지되면 미디어 세트의 전체 데이터베이스 백업에서 데이터베이스를 복원한 후 모든 후속 로그 백업을 복구 지점까지 복원할 수 있습니다.With the log chain intact, you can restore your database from any full database backup in the media set, followed by all subsequent log backups up through your recovery point. 복구 지점은 마지막 로그 백업의 끝이나 로그 백업의 특정 복구 지점일 수 있습니다.The recovery point could be the end of the last log backup or a specific recovery point in any of the log backups. 자세한 내용은 트랜잭션 로그 백업(SQL Server)을 참조하세요.For more information, see Transaction Log Backups (SQL Server).

데이터베이스를 오류 발생 시점까지 복원하려면 로그 체인이 온전해야 합니다.To restore a database up to the point of failure, the log chain must be intact. 즉 트랜잭션 로그 백업의 연속적인 시퀀스가 오류 발생 지점까지 이어져야 합니다.That is, an unbroken sequence of transaction log backups must extend up to the point of failure. 이 로그 시퀀스가 시작되는 위치는 복원 중인 데이터 백업의 유형인 데이터베이스, 부분 또는 파일에 따라 달라집니다.Where this sequence of log must start depends on the type of data backups you are restoring: database, partial, or file. 데이터베이스 또는 부분 백업의 경우 로그 백업의 시퀀스는 데이터베이스 또는 부분 백업의 끝 지점에서 이어져야 합니다.For a database or partial backup, the sequence of log backups must extend from the end of a database or partial backup. 파일 백업 집합의 경우 로그 백업의 시퀀스는 전체 파일 백업 집합의 시작 지점에서 이어져야 합니다.For a set of file backups, the sequence of log backups must extend from the start of a full set of file backups. 자세한 내용은 트랜잭션 로그 백업 적용(SQL Server)을 참조하세요.For more information, see Apply Transaction Log Backups (SQL Server).

로그 백업을 복원하려면Restore Log Backups

로그 백업을 복원하면 현재 데이터베이스를 로그 백업 작업이 시작된 시점의 데이터베이스 상태와 정확히 일치하도록 다시 만들기 위해 트랜잭션 로그에 기록된 변경 내용을 롤포워드합니다.Restoring a log backup rolls forward the changes that were recorded in the transaction log to re-create the exact state of the database at the time the log backup operation started. 데이터베이스를 복원하는 경우 복원하는 전체 데이터베이스 백업 이후 또는 복원하는 첫 번째 파일 백업의 시작 부분에서 만든 로그 백업을 복원해야 합니다.When you restore a database, you will have to restore the log backups that were created after the full database backup that you restore, or from the start of the first file backup that you restore. 일반적으로 가장 최근의 데이터나 차등 백업을 복원하고 나면 복구 지점에 이를 때까지 일련의 로그 백업을 복원한 다음Typically, after you restore the most recent data or differential backup, you must restore a series of log backups until you reach your recovery point. 데이터베이스를 복구해야 합니다.Then, you recover the database. 이때까지 완료되지 않은 트랜잭션은 모두 롤백되며 복구가 완료되면 데이터베이스는 온라인 상태가 됩니다.This rolls back all transactions that were incomplete when the recovery started and brings the database online. 데이터베이스가 복구된 후에는 더 이상의 백업을 복원할 수 없습니다.After the database has been recovered, you cannot restore any more backups. 자세한 내용은 트랜잭션 로그 백업 적용(SQL Server)을 참조하세요.For more information, see Apply Transaction Log Backups (SQL Server).

검사점 및 로그의 활성 부분Checkpoints and the Active Portion of the Log

검사점은 현재 데이터베이스의 버퍼 캐시에 있는 커밋되지 않은 데이터 페이지를 디스크로 플러시합니다.Checkpoints flush dirty data pages from the buffer cache of the current database to disk. 따라서 데이터베이스의 전체 복구 중에 처리되어야 하는 로그의 활성 부분이 최소화됩니다.This minimizes the active portion of the log that must be processed during a full recovery of a database. 전체 복구 동안 다음 유형의 동작이 수행됩니다.During a full recovery, the following types of actions are performed:

  • 시스템이 중지되기 전에 디스크로 플러시되지 않은 로그의 수정 레코드가 롤포워드됩니다.The log records of modifications not flushed to disk before the system stopped are rolled forward.
  • 커밋 또는 롤백 로그 레코드가 없는 불완전한 트랜잭션과 관련된 모든 수정 내용이 롤백됩니다.All modifications associated with incomplete transactions, such as transactions for which there is no COMMIT or ROLLBACK log record, are rolled back.

검사점 작업Checkpoint Operation

데이터베이스에서 검사점이 수행하는 프로세스는 다음과 같습니다.A checkpoint performs the following processes in the database:

  • 검사점의 시작을 표시하는 레코드를 로그 파일에 기록합니다.Writes a record to the log file, marking the start of the checkpoint.
  • 검사점 로그 레코드의 체인에 검사점에 대해 기록된 정보를 저장합니다.Stores information recorded for the checkpoint in a chain of checkpoint log records.

    검사점에 기록되는 한 가지 정보는 성공적인 데이터베이스 차원의 롤백을 위해 반드시 있어야 하는 첫 번째 로그 레코드의 LSN(로그 시퀀스 번호)입니다.One piece of information recorded in the checkpoint is the log sequence number (LSN) of the first log record that must be present for a successful database-wide rollback. 이 LSN을 최소 복구 LSN(MinLSN)이라고 합니다.This LSN is called the Minimum Recovery LSN (MinLSN). MinLSN은 다음의 최소값입니다.The MinLSN is the minimum of the:

    • 검사점 시작의 LSNLSN of the start of the checkpoint.
    • 가장 오래된 활성 트랜잭션 시작의 LSNLSN of the start of the oldest active transaction.
    • 아직 배포 데이터베이스로 전달되지 않은 가장 오래된 복제 트랜잭션 시작의 LSNLSN of the start of the oldest replication transaction that has not yet been delivered to the distribution database.

      또한 검사점 레코드에는 데이터베이스를 수정한 모든 활성 트랜잭션 목록이 포함됩니다.The checkpoint records also contain a list of all the active transactions that have modified the database.

  • 데이터베이스에서 단순 복구 모델을 사용하는 경우 MinLSN 앞에 나오는 공간을 재사용 가능으로 표시합니다.If the database uses the simple recovery model, marks for reuse the space that precedes the MinLSN.

  • 커밋되지 않은 모든 로그와 데이터 페이지를 디스크에 씁니다.Writes all dirty log and data pages to disk.
  • 검사점의 끝을 표시하는 레코드를 로그 파일에 씁니다.Writes a record marking the end of the checkpoint to the log file.
  • 이 체인의 시작 LSN을 데이터베이스 부팅 페이지에 씁니다.Writes the LSN of the start of this chain to the database boot page.

검사점을 발생시키는 작업Activities that cause a Checkpoint

검사점은 다음과 같은 상황에서 발생합니다.Checkpoints occur in the following situations:

  • CHECKPOINT 문이 명시적으로 실행된 경우.A CHECKPOINT statement is explicitly executed. 현재 연결된 데이터베이스에서 검사점이 발생합니다.A checkpoint occurs in the current database for the connection.
  • 데이터베이스에서 최소 로그 작업이 수행된 경우(예: 대량 로그 복구 모델을 사용하는 데이터베이스에서 대량 복사 작업이 수행된 경우)A minimally logged operation is performed in the database; for example, a bulk-copy operation is performed on a database that is using the Bulk-Logged recovery model.
  • ALTER DATABASE를 사용하여 데이터베이스 파일을 추가 또는 제거한 경우Database files have been added or removed by using ALTER DATABASE.
  • SHUTDOWN 문을 사용하거나 SQL Server(MSSQLSERVER) 서비스를 중지하여 SQL Server 인스턴스를 중지한 경우.An instance of SQL Server is stopped by a SHUTDOWN statement or by stopping the SQL Server (MSSQLSERVER) service. 두 동작은 모두 SQL Server 인스턴스의 각 데이터베이스에 검사점을 설정합니다.Either action causes a checkpoint in each database in the instance of SQL Server.
  • SQL Server 인스턴스가 데이터베이스를 복구하는 데 걸리는 시간을 줄이기 위해 각 데이터베이스에서 자동 검사점을 주기적으로 생성하는 경우An instance of SQL Server periodically generates automatic checkpoints in each database to reduce the time that the instance would take to recover the database.
  • 데이터베이스를 백업한 경우A database backup is taken.
  • 데이터베이스를 종료해야 하는 작업을 수행한 경우.An activity requiring a database shutdown is performed. AUTO_CLOSE가 on이고 데이터베이스에 대한 마지막 사용자 연결이 닫힌 경우 또는 데이터베이스를 다시 시작해야 하는 데이터베이스 옵션 변경을 수행한 경우를 예로 들 수 있습니다.For example, AUTO_CLOSE is on and the last user connection to the database is closed, or a database option change is made that requires a restart of the database.

자동 검사점Automatic Checkpoints

SQL Server 데이터베이스 엔진은 자동 검사점을 생성합니다.The SQL Server Database Engine generates automatic checkpoints. 자동 검사점 간의 간격은 마지막 검사점 이후 경과된 시간과 사용된 로그 공간에 따라 결정됩니다.The interval between automatic checkpoints is based on the amount of log space used and the time elapsed since the last checkpoint. 데이터베이스가 거의 수정되지 않을 경우에는 자동 검사점 간의 시간 간격이 가변적이고 길어질 수 있습니다.The time interval between automatic checkpoints can be highly variable and long, if few modifications are made in the database. 또한 많은 데이터를 수정할 경우에는 자동 검사점이 자주 발생할 수 있습니다.Automatic checkpoints can also occur frequently if lots of data is modified.

복구 간격 서버 구성 옵션을 사용하여 서버 인스턴스의 모든 데이터베이스에 대한 자동 검사점 간 간격을 계산할 수 있습니다.Use the recovery interval server configuration option to calculate the interval between automatic checkpoints for all the databases on a server instance. 이 옵션은 시스템을 다시 시작하는 동안 데이터베이스 엔진이 데이터베이스를 복구하는 데 사용하는 최대 시간을 지정합니다.This option specifies the maximum time the Database Engine should use to recover a database during a system restart. 데이터베에스 엔진은 복구 작업 중에 해당 복구 간격 동안 처리할 수 있는 로그 레코드의 수를 예상합니다.The Database Engine estimates how many log records it can process in the recovery interval during a recovery operation.

자동 검사점 간의 간격은 복구 모델에 따라서도 달라집니다.The interval between automatic checkpoints also depends on the recovery model:

  • 전체 또는 대량 로그 복구 모델을 사용하는 데이터베이스의 경우 로그 레코드의 수가 데이터베이스 엔진에서 복구 간격 옵션에 지정된 시간 동안 처리할 수 있다고 예상한 레코드의 수에 도달할 때마다 자동 검사점이 생성됩니다.If the database is using either the full or bulk-logged recovery model, an automatic checkpoint is generated whenever the number of log records reaches the number the Database Engine estimates it can process during the time specified in the recovery interval option.
  • 단순 복구 모델을 사용하는 데이터베이스의 경우 로그 레코드의 수가 다음의 두 값 중에서 작은 값에 도달할 때마다 자동 검사점이 생성됩니다.If the database is using the simple recovery model, an automatic checkpoint is generated whenever the number of log records reaches the lesser of these two values:

    • 로그의 70%가 찼을 때The log becomes 70 percent full.
    • 로그 레코드의 수가 데이터베이스 엔진에서 복구 간격 옵션에 지정된 시간 동안 처리할 수 있다고 예상한 수에 도달했을 때The number of log records reaches the number the Database Engine estimates it can process during the time specified in the recovery interval option.

복구 간격 설정에 대한 자세한 내용은 복구 간격 서버 구성 옵션 구성을 참조하세요.For information about setting the recovery interval, see Configure the recovery interval Server Configuration Option.

데이터베이스 관리자는 일부 유형의 검사점에 대해 -k SQL Server 고급 설정 옵션을 사용하여 I/O 하위 시스템의 처리량에 따라 검사점 I/O 동작을 제한할 수 있습니다.The -k SQL Server advanced setup option enables a database administrator to throttle checkpoint I/O behavior based on the throughput of the I/O subsystem for some types of checkpoints. -k 설정 옵션은 자동 검사점과 그 밖의 제한되지 않는 모든 검사점에 적용됩니다.The -k setup option applies to automatic checkpoints and any otherwise unthrottled checkpoints.

자동 검사점은 데이터베이스가 단순 복구 모델을 사용하고 있을 때 트랜잭션 로그의 사용되지 않는 부분을 자릅니다.Automatic checkpoints truncate the unused section of the transaction log if the database is using the simple recovery model. 그러나 데이터베이스가 전체 또는 대량 로그 복구 모델을 사용하고 있을 때는 자동 검사점에서 이러한 로그를 자르지 않습니다.However, if the database is using the full or bulk-logged recovery models, the log is not truncated by automatic checkpoints. 자세한 내용은 트랜잭션 로그를 참조하세요.For more information, see The Transaction Log.

이제 CHECKPOINT 문에서는 검사점을 완료하는 요청 시간(초)을 지정하는 선택적 checkpoint_duration 인수를 제공합니다.The CHECKPOINT statement now provides an optional checkpoint_duration argument that specifies the requested period of time, in seconds, for checkpoints to finish. 자세한 내용은 CHECKPOINT를 참조하세요.For more information, see CHECKPOINT.

활성 로그Active Log

MinLSN에서 마지막으로 쓰여진 로그 레코드까지의 로그 파일 섹션을 로그의 활성 부분 또는 활성 로그라고 합니다.The section of the log file from the MinLSN to the last-written log record is called the active portion of the log, or the active log. 로그의 이 섹션은 데이터베이스의 전체 복구를 수행하는 데 필요합니다.This is the section of the log required to do a full recovery of the database. 활성 로그는 어떤 부분도 잘라낼 수 없습니다.No part of the active log can ever be truncated. 모든 로그 레코드는 로그의 MinLSN 앞에서 잘라야 합니다.All log records must be truncated from the parts of the log before the MinLSN.

다음 그림에서는 두 개의 활성 트랜잭션이 있는 트랜잭션 로그 끝의 단순화된 버전을 보여 줍니다.The following illustration shows a simplified version of the end-of-a-transaction log with two active transactions. 검사점 레코드는 단일 레코드로 압축되었습니다.Checkpoint records have been compacted to a single record.

active_log

LSN 148은 트랜잭션 로그의 마지막 레코드입니다.LSN 148 is the last record in the transaction log. LSN 147에 기록된 검사점이 처리되면 Tran 1이 커밋되고 Tran 2만 유일한 활성 트랜잭션이 됩니다.At the time that the recorded checkpoint at LSN 147 was processed, Tran 1 had been committed and Tran 2 was the only active transaction. 이 경우 Tran 2에 대한 첫 번째 로그 레코드가 마지막 검사점에서 활성 상태인 트랜잭션에 대한 가장 오래된 로그 레코드가 됩니다.That makes the first log record for Tran 2 the oldest log record for a transaction active at the time of the last checkpoint. 따라서 Tran 2에 대한 Begin Transaction 레코드인 LSN 142가 MinLSN이 됩니다.This makes LSN 142, the Begin transaction record for Tran 2, the MinLSN.

장기 실행 트랜잭션Long-Running Transactions

활성 로그에는 커밋되지 않은 모든 트랜잭션의 모든 부분이 포함되어야 합니다.The active log must include every part of all uncommitted transactions. 트랜잭션을 시작했으나 커밋하거나 롤백하지 않은 응용 프로그램이 있으면 데이터베이스 엔진이 MinLSN을 앞당기지 못하게 됩니다.An application that starts a transaction and does not commit it or roll it back prevents the Database Engine from advancing the MinLSN. 이로 인해 다음 두 가지 유형의 문제가 발생할 수 있습니다.This can cause two types of problems:

  • 트랜잭션이 커밋되지 않은 많은 수정 작업을 수행한 후에 시스템이 종료되면 시스템이 다시 시작된 후의 복구 단계 수행 시 복구 간격 옵션에 지정된 시간보다 훨씬 더 오래 걸릴 수 있습니다.If the system is shut down after the transaction has performed many uncommitted modifications, the recovery phase of the subsequent restart can take much longer than the time specified in the recovery interval option.
  • 로그가 MinLSN을 통과하여 잘릴 수 없으므로 너무 커질 수 있습니다.The log might grow very large, because the log cannot be truncated past the MinLSN. 이러한 문제는 트랜잭션 로그가 각 자동 검사점에서 일반적으로 잘리게 되는 단순 복구 모델을 데이터베이스에서 사용하는 경우에도 발생합니다.This occurs even if the database is using the simple recovery model, in which the transaction log is generally truncated on each automatic checkpoint.

복제 트랜잭션Replication Transactions

로그 판독기 에이전트는 트랜잭션 복제를 위해 구성한 각 데이터베이스의 트랜잭션 로그를 모니터링하고 복제 표시된 트랜잭션을 트랜잭션 로그에서 배포 데이터베이스로 복사합니다.The Log Reader Agent monitors the transaction log of each database configured for transactional replication, and it copies the transactions marked for replication from the transaction log into the distribution database. 활성 로그에는 복제용으로 표시되었지만 아직 배포 데이터베이스로 전달되지 않은 모든 트랜잭션이 포함되어야 합니다.The active log must contain all transactions that are marked for replication, but that have not yet been delivered to the distribution database. 이러한 트랜잭션이 제때에 복제되지 않으면 로그 잘라내기가 수행되지 않을 수 있습니다.If these transactions are not replicated in a timely manner, they can prevent the truncation of the log. 자세한 내용은 트랜잭션 복제를 참조하세요.For more information, see Transactional Replication.

관련 항목:See also

트랜잭션 로그 및 로그 관리 모범 사례에 대한 자세한 내용은 다음 문서 및 서적을 참조하세요.We recommend the following articles and books for additional information about the transaction log and log management best practices.

트랜잭션 로그(SQL Server) The Transaction Log (SQL Server)
트랜잭션 로그 파일의 크기 관리 Manage the size of the transaction log file
트랜잭션 로그 백업(SQL Server) Transaction Log Backups (SQL Server)
데이터베이스 검사점(SQL Server) Database Checkpoints (SQL Server)
recovery interval 서버 구성 옵션 구성 Configure the recovery interval Server Configuration Option
sys.dm_db_log_info (Transact-SQL) sys.dm_db_log_info (Transact-SQL)
sys.dm_db_log_space_usage (Transact-SQL) sys.dm_db_log_space_usage (Transact-SQL)
Paul Randall, “SQL Server의 로깅 및 복구 이해” Understanding Logging and Recovery in SQL Server by Paul Randal
Tony Davis 및 Gail Shaw 공저, "SQL Server 트랜잭션 로그 관리"SQL Server Transaction Log Management by Tony Davis and Gail Shaw